Get Windows UserName
When constructing the path to the "My Documents" directory, it is sometimes necessary to construct the path using the Windows login username. This example shows how to open a workbook stored in a user directory:
Program Code
Option Explicit
Private Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Public Sub GetTemplatePath()
Dim strPathToJobInfoTemplate As String
Dim wkbJobInfoWorkbook As Workbook
strPathToJobInfoTemplate = "C:\Users\" & UserNameWindows() & "\Documents\JobInfoTemplate\JobInfoTemplate.xlsm"
Workbooks.Open strPathToJobInfoTemplate
Set wkbJobInfoWorkbook = ActiveWorkbook
End Sub
Function UserNameWindows() As String
Dim lngLen As Long
Dim strBuffer As String
Const dhcMaxUserName = 255
strBuffer = Space(dhcMaxUserName)
lngLen = dhcMaxUserName
If CBool(GetUserName(strBuffer, lngLen)) Then
UserNameWindows = Left$(strBuffer, lngLen - 1)
Else
UserNameWindows = ""
End If
End Function