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
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
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.