環境變量是不可靠的
- 的用戶可以將值編輯爲任何他們想要的值
- 用戶可以刪除環境變量。
嘗試這些API方法之一。
選項1
Private Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" _
(ByVal lpBuffer As String, nSize As Long) As Long
Sub Sample()
Dim lpBuff As String * 25
Dim ret As Long, UserName As String
ret = GetUserName(lpBuff, 25)
UserName = Left(lpBuff, InStr(lpBuff, Chr(0)) - 1)
MsgBox UserName
End Sub
選項2
Option Explicit
Private Declare Function GetEnvironmentVariable Lib _
"kernel32" Alias "GetEnvironmentVariableA" _
(ByVal lpName As String, ByVal lpBuffer As String, _
ByVal nSize As Long) As Long
Private Sub Sample()
Dim strUserName As String * 255
Dim x As Integer
x = GetEnvironmentVariable("USERNAME", strUserName, Len(strUserName))
If x > 0 Then
x = InStr(strUserName, vbNullChar)
If x > 0 Then
MsgBox (Left$(strUserName, x - 1))
Else
MsgBox (Left$(strUserName, x))
End If
End If
End Sub
感謝您的建議。我會在星期一嘗試一下,看看它是否有效。 – John
,也爲我工作。非常感謝您的幫助。 – John