I\'m really confused about passing strings from VBA to C++. Here\'s the VBA code:
Private Declare Sub passBSTRVal Lib \"
This form of external function call exists to be compatible with earlier versions of Visual Basic, and inherits their semantics. In particular, VB3 ran on 16-bit windows and dealt only with ANSI (i.e. MBCS) strings.
The Declare
syntax has the same restriction. VBA converts your string on the assumption that it is converting it from UTF-16 to ASCII. This allows code written in VB3 to work unchanged in VB4, VB5 and VB6.
So for example "AZ" begins as \u0041\u005A
, is converted to ANSI and becomes \x41\x5A
which is reinterpreted as \u5A41
which is "婁".
(With VB4, Microsoft merged WordBasic, Excel Basic and Visual basic into a single language, VBA.)
The "new" way to call functions from VBA, is to create a type library for the external functions you need to use, using MIDL, and add it as a reference to the project. Type libraries can describe the exact signature of the function, (e.g. BSTR
, LPCSTR
, LPCWSTR
, [out]BSTR*
, etc.) In particular it is not necessary to wrap the functions in a COM object to call them from VBA (though it is if you wish to call them from VBScript).
module
: https://msdn.microsoft.com/en-us/library/windows/desktop/aa367099(v=vs.85).aspxAlternatively you can't be bothered to fire up midl
for a single function, you can use the VarPtr
/StrPtr
/CopyMemory
hack. This is pretty much equivalent to PEEK
and POKE
.