G
Guest
Sometimes, there are various ways to achieve the same thing. Let's say you're
making an Access DB, and you need to know the user name of the person
currently logged on to the PC (not the DB, the PC). Here's two methods,
although I'm sure there's more.
You could use a Windows API call, like this:
Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" _
(ByVal lpBuffer As String, nSize As Long) As Long
Sub Get_User_Name()
Dim lpBuff As String * 25
Dim ret As Long, UserName As String
ret = GetUserName(lpBuff, 25)
UserName = Left(lpBuff, InStr(lpBuff, Chr(0)) - 1)
Debug.Print UserName
End Sub
....or, you could use a scripting host, like this:
Public Function ListUserName()
Dim strComputer As String
Dim objWMIService As Object
Dim colComputer As Object
Dim objComputer As Object
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colComputer = objWMIService.ExecQuery _
("Select * from Win32_ComputerSystem")
For Each objComputer In colComputer
Debug.Print objComputer.UserName
Next
End Function
Is there any advantages / disadvanages to using either the Windows API or
the scripting method? Performance? Memory usage? Less chance of Microsoft
changing it so it won't work anymore? I'd love to hear ideas....
Thanks!
making an Access DB, and you need to know the user name of the person
currently logged on to the PC (not the DB, the PC). Here's two methods,
although I'm sure there's more.
You could use a Windows API call, like this:
Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" _
(ByVal lpBuffer As String, nSize As Long) As Long
Sub Get_User_Name()
Dim lpBuff As String * 25
Dim ret As Long, UserName As String
ret = GetUserName(lpBuff, 25)
UserName = Left(lpBuff, InStr(lpBuff, Chr(0)) - 1)
Debug.Print UserName
End Sub
....or, you could use a scripting host, like this:
Public Function ListUserName()
Dim strComputer As String
Dim objWMIService As Object
Dim colComputer As Object
Dim objComputer As Object
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colComputer = objWMIService.ExecQuery _
("Select * from Win32_ComputerSystem")
For Each objComputer In colComputer
Debug.Print objComputer.UserName
Next
End Function
Is there any advantages / disadvanages to using either the Windows API or
the scripting method? Performance? Memory usage? Less chance of Microsoft
changing it so it won't work anymore? I'd love to hear ideas....
Thanks!