Wednesday, July 2, 2008

Get the Logged in Users Name

To get the name of the currently logged in user, you need to first, create a function to call a Windows API function to get the user name.  The function looks like this;

 

 'Define the Window API Function
Public Declare Function GetUserName Lib "advapi32.dll" _
Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long

 

'This is Function Returns the user name of the currently logged in user
'This works in Windows 95, XP and Vista

Function ReturnUserName() As String
Dim rString As String * 255, sLen As Long, tString As String
    tString = ""
    On Error Resume Next
    sLen = GetUserName(rString, 255)
    sLen = InStr(1, rString, Chr(0))
    If sLen > 0 Then
        tString = Left(rString, sLen - 1)
    Else
        tString = rString
    End If
    On Error GoTo 0
    ReturnUserName = UCase(Trim(tString))
End Function

 

Next, within your macro code, call the function and the username will be returned in a variable.  For example;

 

cUser = ReturnUserName()

 

...will return the username in a variable called cUser.

No comments:

Time Math in Excel

You can use the TIME() function to add or subtract hours, minutes or seconds in Excel.  The TIME function takes 3 parameters; HOURS, MINUTES...