如果要獲取Windows默認的用戶帳戶名稱,可以使用下面的VBA代碼,其中使用了 WNetGetUser 函數,將代碼放入標準模塊中:
Option Explicit
Private Declare Function WNetGetUser Lib "mpr.dll" Alias "WNetGetUserA" _
(ByVal lpName As String, _
ByVal lpUserName As String, _
lpnLength As Long) As Long
Private Const NO_ERROR = 0
Private Const ERROR_NOT_CONNECTED = 2250&
Private Const ERROR_MORE_DATA = 234
Private Const ERROR_NO_NETWORK = 1222&
Private Const ERROR_EXTENDED_ERROR = 1208&
Private Const ERROR_NO_NET_OR_BAD_PATH = 1203&
Sub Getusername()
Dim strBuf As String, lngUser As Long, strUn As String
strBuf = Space$(255) ‘//Clear buffer
lngUser = WNetGetUser("", strBuf, 255)
If lngUser = NO_ERROR Then
strUn = Left(strBuf, InStr(strBuf, vbNullChar) – 1)
MsgBox "系統用戶帳戶名稱是: " & strUn
Else
MsgBox "錯誤:" & lngUser
End If
End Sub