2

I have VBA MS Access form code, where I type the following function declaration:

Public Declare Function GetUserName Lib "advapi32.dll" () Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long

However I'm getting an error on Alias. Do I have to add some references in order to use this?

1 Answer 1

6

No, there are no special libraries are required to use Alias; this is all built into the language.

But your declaration is wrong. You have an extra set of parentheses placed just before Alias that are confusing the compiler.

Beyond pure syntax, the second parameter (nSize) is actually a pointer to a Long, which means that you need to pass it ByRef in VBA.

So the revised declaration would look like this, instead:

Public Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" _
        (ByVal lpBuffer As String, ByRef nSize As Long) As Long

The return value will be 1 if the function succeeds, or 0 if it fails.

Sign up to request clarification or add additional context in comments.

3 Comments

Declaring an API functino As Boolean is an overkill IMO. "Proper" VB booleans are longs constrained to 0/-1 but you can use CopyMemory to force any value, non-zero being true. This is what As Boolean on the API declare will do -- hide a 1 in a boolean. Using such "hacked" values in bool expressions can have strange side effects like bValue1 And bValue2 being false on both vars being true.
@wqw Quite correct. it can also lead to Not bValue being True when bValue is also True. Don't use Boolean in Declare against the Windows API
VB 6 really doesn't know how to marshal data types any better than that? Yes, it represents boolean data types differently internally than other common programming languages, and BOOL in the WinAPI isn't a boolean data type at all. But I've never had a problem making it work as expected. I guess my expectations are artificial. Declare it either way you want; if it's a Long, then TRUE will be 1 and FALSE will be 0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.