A site for solving at least some of your technical problems...
A site for solving at least some of your technical problems...
These are common questions for MS-Access users:
Both names are available in the Kernel and we can make use of a function declaration to access those names.
To determine the name of the current user:
Private Declare Function GetUserName Lib "advapi32.dll" _ Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long Public Function GetLogonName() As String Dim lpBuf As String * 255 Dim ret As Long ret = GetUserName(lpBuf, 255) If ret > 0 Then GetLogonName = Left(lpBuf, InStr(lpBuf, Chr(0)) - 1) Else GetLogonName = vbNullString End If End Function
As we can see we call the GetUserName() function with a buffer of exactly 255 characters and then make sure it was defined by the call. If so, we resize the output searching the C string null terminator.
The computer name function is exactly the same, only it calls GetComputerNameA instead:
Private Declare Function GetComputerName Lib "kernel32.dll" _ Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long Public Function GetHostComputerName() As String Dim lpBuf As String * 255 Dim ret As Long ret = GetComputerName(lpBuf, 255) If ret > 0 Then GetHostComputerName = Left(lpBuf, InStr(lpBuf, Chr(0)) - 1) Else GetHostComputerName = vbNullString End If End Function
Important note: If you want to define both functions in the same module, then you must put both Private Declare Function ... instructions before BOTH functions.
These functions take the names as defined by the system. It is also possible to make use of the Environ("username") and Environ("computername") functions, however, by default the Environ() and Environ$() functions are hidden. The environment variables are considered unsafe and thus they should not be used.
Yet, two points to be noted (1) Windows 7 "untaints" the environment variables—it forces the values of well defined variables making them safe no matter what 1; (2) your module functions will NOT be directly available in SQL statements, whereas the Environ() functions are.