简体   繁体   中英

Excel VBA - string param pass from excel but not from VBA

I have DLL function which has two string parameters and two int parameters. The function returns a string. When I call the function directly from excel, it is OK, but when I call the function from VBA, to DLL function is pass string params , which is not corresponding with original (nonsense characters). And function return string , witch have every seconds char " " .

My dll function looks like this:

BSTR __stdcall getPattern(int sex, int pad, BSTR * a, BSTR * b){
    ...
}

Declare function in VBA:

Declare Function GetPattern _
Lib "myPathToFunction" Alias "GetPattern" (ByVal poh As Integer, ByVal pad As Integer, ByRef a As String, ByRef b As String) As String

In excel I call the function like this: (And it is OK)

=GetPattern(I5;C1;A1;B1)

And from VBA call function like this: (and it return only first char of string)

result = GetPattern(Range("I5").Value, Range("C1").Value, Cells(i, 1).Value, Cells(i, 2).Value)

This could be an issue with VB converting strings to ANSI on C calls. You may need to explicitly pass a string pointer:

Dim param_a As String
Dim param_b As String

param_a = Cells(i, 1).Value
param_b = Cells(i, 2).Value
result = GetPattern(Range("I5").Value, Range("C1").Value, _
                    StrPtr(param_a), StrPtr(param_b))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM