Windows Username


Posted by Ken Mamak on January 08, 2002 7:31 AM

I need to capture the windows login name in excel (this is different from the application.username). Is there a way to do that ?
Please email me at ken@liteweb.com
Thanks

Ken

Posted by faster on January 08, 2002 7:55 AM

You can use API. Copy this code into a module and run it.


Private Declare Function w32_WNetGetUser Lib "mpr.dll" Alias "WNetGetUserA" (ByVal lpszLocalName As String, ByVal lpszUserName As String, lpcchBuffer As Long) As Long
Private Sub Form_Load()

'code from http://www.allapi.net/
Dim lpUserName As String, lpnLength As Long, lResult As Long
'Create a buffer
lpUserName = String(256, Chr$(0))
'Get the network user
lResult = w32_WNetGetUser(vbNullString, lpUserName, 256)
If lResult = 0 Then
lpUserName = Left$(lpUserName, InStr(1, lpUserName, Chr$(0)) - 1)
MsgBox "The user's Network Logon Name is " + lpUserName
Else
MsgBox "No user found !"
End If
End Sub

Posted by Andy Gee on January 08, 2002 8:30 AM

I modified the code you posted but would like it to load automatically, when I open my stock sheet.

Private Declare Function w32_WNetGetUser Lib "mpr.dll" Alias "WNetGetUserA" (ByVal lpszLocalName As String, ByVal lpszUserName As String, lpcchBuffer As Long) As Long
Private Sub Form_Load()
Dim lpUserName As String, lpnLength As Long, lResult As Long
lpUserName = String(256, Chr$(0))
lResult = w32_WNetGetUser(vbNullString, lpUserName, 256)
If lResult = 0 Then
lpUserName = Left$(lpUserName, InStr(1, lpUserName, Chr$(0)) - 1)
myname = "Andy Geer"
If lpUserName = myname Then Exit Sub
End If
MsgBox "Unauthorised access " + lpUserName + " Your access has been logged"
filepath = "C:\excel.log"
Open filepath For Output As #1
Print #1, lpUserName
Close #1

End Sub


I know it's not very secure as someone could just delete the log file but it may scare my colegues a bit. Any help would be cool

Posted by faster on January 08, 2002 9:25 AM

Maybe put the code in the OnOpen event. You may need
to rename the sub. I have used the code to log
the users in a very-hidden sheet; without the user knowing
it. Then they won't be tempted to delete it.



Posted by Andy Gee on January 08, 2002 9:36 AM

Thanks!


Thanks