tags:

views:

72

answers:

6

I can use Application.Username in Excel's VBA editor to return the username of the current user. What is the equivalent in VB6?

A: 

TechRepublic has a good quick writeup on this:

Determine the current username in VB6

Justin Niessner
+1  A: 

You can call the Windows API -

http://msdn.microsoft.com/en-us/library/ms724432(VS.85).aspx

Lloyd
A: 

GetUserNameEx is the recommended way to retrieve the Windows user name. See the second post on this thread for a VB6 example. http://www.codeguru.com/forum/showthread.php?t=347275

Joe
+1  A: 

Here is a routine from one of my standard libraries. I think I included everything you need.

Private Const VER_PLATFORM_WIN32_NT = 2

Private Type OSVERSIONINFO
   dwOSVersionInfoSize As Long
   dwMajorVersion As Long
   dwMinorVersion As Long
   dwBuildNumber As Long
   dwPlatformId As Long
   szCSDVersion As String * 128      '  Maintenance string for PSS usage'
End Type

Public Enum EXTENDED_NAME_FORMAT
   NameUnknown = 0
   NameFullyQualifiedDN = 1
   NameSamCompatible = 2
   NameDisplay = 3
   NameUniqueId = 6
   NameCanonical = 7
   NameUserPrincipal = 8
   NameCanonicalEx = 9
   NameServicePrincipal = 10
   NameDnsDomain = 12
End Enum

Private Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Private Declare Function GetUserNameEx Lib "Secur32.dll" Alias "GetUserNameExA" (ByVal NameFormat As EXTENDED_NAME_FORMAT, ByVal lpNameBuffer As String, ByRef lpnSize As Long) As Long
Private Declare Function GetVersionEx Lib "kernel32" Alias "GetVersionExA" (lpVersionInformation As OSVERSIONINFO) As Long

Public Function UserName() As String
   Dim sBuff As String * 260
   Dim lBuffLen As Long
   Dim Rtn As Long
   Dim sReturn As String

   On Error GoTo errUserName

   lBuffLen = Len(sBuff)
   sBuff = Space$(lBuffLen)
   If IsWindows2kOrBetter = True Then
      Rtn = GetUserNameEx(NameDisplay, sBuff, lBuffLen)
   Else
      Rtn = GetUserName(sBuff, lBuffLen)
   End If
   If Rtn <> 0 Then
      sReturn = Left$(sBuff, lBuffLen - 1)
   Else
      sReturn = ""
   End If
   UserName = sReturn

    Exit Function

errUserName:
   UserName = ""

End Function

Public Function IsWindows2kOrBetter() As Boolean
   Dim blnReturn As Boolean
   Dim lngRst As Long
   Dim oVerInfo As OSVERSIONINFO

   oVerInfo.dwOSVersionInfoSize = Len(oVerInfo)
   lngRst = GetVersionEx(oVerInfo)
   If lngRst > 0 Then
      If oVerInfo.dwPlatformId = VER_PLATFORM_WIN32_NT And oVerInfo.dwMajorVersion >= 5 Then
         blnReturn = True
      Else
         blnReturn = False
      End If
   Else
      blnReturn = False
   End If

   IsWindows2kOrBetter = blnReturn

End Function
Beaner
A: 

You can generally use:Environ$("USERNAME")

Oorang