Network Username in Access VBA - ΩJr. Software Articles and Products

This information lives on a web page hosted at the following web address: 'https://omegajunior.globat.com/code/'.

Use the built-in Environ()-method, and when that yields no results or cannot be used at all, use the GetUserName() api. Full code sample below.

A.E.Veltstra
3 May, 2004

People using your Microsoft Access application log into their network and don't want to log into your application as well. Use the function below to retrieve their network user name.


Code: Environ()


UserNameVba = VBA.Interaction.Environ("USERNAME")

Code: GetUserName()


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

Public Function UserNameApi() As String
Dim strReturn As String, nSize As Long, lngRet As Long

'GetUserName fills strReturn with a name
'and ends with a 0-char.
strReturn = String(256, Chr(0))
nSize = Len(strReturn)

'will fail when length of strReturn is too small
lngRet = GetUserName(strReturn, nSize)

If lngRet = 0 Then 'failure
If nSize > 0 Then 'buffer overflow (ERROR_MORE_DATA)

'nSize contains necessary length
strReturn = String(nSize, Chr(0))

lngRet = GetUserName(strReturn, nSize)

End If
End If

'If strReturn contains a 0-char,
'the username is everything in front of it.
nSize = InStr(1, strReturn, Chr(0))

If nSize > 0 Then
UserNameApi = Left(strReturn, nSize - 1)
Else
UserNameApi = strReturn
End If

End Function



Keywords
vb, vba, vbscript, visual basic, access, api, username, user name, network, environment

Need problem solving?

Talk to me. Let's meet for coffee or over lunch. Mail me at “omegajunior at protonmail dot com”.