win api function

  • Thread starter Thread starter Randy
  • Start date Start date
R

Randy

Inside of a VBA / excel macro, is there a function I can
call to get the nt login of the current user?

Any help much appreciated.

Randy
 
Hi Randy,

Here's a response I posted the other day to m.p.e.misc:


You can get the username from one of two places:

1) an environment variable:

MsgBox Environ$("Username")

2) the Windows API:

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

Public Function gsGetUsername() As String
Dim sName As String * 255
Dim nPos As Integer

GetUserName sName, 255
nPos = InStr(1, sName, vbNullChar)
If nPos Then gsGetUsername = Left$(sName, nPos - 1)
End Function

MsgBox gsGetUsername

I typically use #2, as I feel it is more reliable than #1. In your
Workbook_Open routine (double-click ThisWorkbook in the VBE to get to the
applicable codepane), you could check to see if a cell has a value - if not,
put the username there:

Private Sub Workbook_Open()
If Len(Sheets("Sheet1").Range("A1").Value) = 0 Then
Sheets("Sheet1").Range("A1").Value = gsGetUsername
End If
End Sub

--
Regards,

Jake Marx
MS MVP - Excel
www.longhead.com

[please keep replies in the newsgroup - email address unmonitored]
 
Back
Top