May 22, 2024


Welcome to the core

Windows Username in a Cell

This is some VBA code that when a workbook is opened the username used to log into windows will be displayed in a cell, in the example its in C1. This needs to be added to either “ThisWorkbook” or added to a button if you fancy.


Declare Function WNetGetUser Lib “mpr.dll.” _
      Alias “WNetGetUserA” (ByVal lpName As String, _
      ByVal lpUserName As String, lpnLength As Long) As Long
   Const NoError = 0       ‘The Function call was successful
   Private Sub workbook_Open()
      ‘ Buffer size for the return string.
      Const lpnLength As Integer = 255
      ‘ Get return buffer space.
      Dim status As Integer
      ‘ For getting user information.
      Dim lpName, lpUserName As String
      ‘ Assign the buffer size constant to lpUserName.
      lpUserName = Space$(lpnLength + 1)
      ‘ Get the log-on name of the person using product.
      status = WNetGetUser(lpName, lpUserName, lpnLength)
      ‘ See whether error occurred.
      If status = NoError Then
         ‘ This line removes the null character. Strings in C are null-
         ‘ terminated. Strings in Visual Basic are not null-terminated.
         ‘ The null character must be removed from the C strings to be used
         ‘ cleanly in Visual Basic.
         lpUserName = Left$(lpUserName, InStr(lpUserName, Chr(0)) – 1)
         ‘ An error occurred.
         MsgBox “Unable to get the name.”
      End If
      ‘ Display the nfame of the person logged on to the machine.
      ‘MsgBox “The person logged on this machine is: ” & lpUserName
       Worksheets(1).Range(“C1“).Value = lpUserName
   End Sub
If you change the bold C1 this will change the location of the username.
Copyright © All rights reserved. | Newsphere by AF themes.