Sign in with Microsoft
Sign in or create an account.
Hello,
Select a different account.
You have multiple accounts
Choose the account you want to sign in with.

摘要

您可以調用 Windows API(應用程式開發介面)到 Microsoft Windows DLL(動態連結程式庫)以獲取當前使用者名稱。 可以使用 ADVAPI32.DLL 中的 GetUserNameA 函數獲取當前使用者名稱。

其他相關資訊

Microsoft Excel 沒有存取電腦當前使用者名稱的內建功能。 但是,您可以使用 Visual Basic 中的 Declare 陳述式讓應用程式巨集來調用會回傳當前使用者名稱的 Microsoft Windows 函數。


Microsoft 僅提供示範性的程式程序 Visual Basic 設計,不做任何明示或默示的保證,其中包括 (但不限) 其適售性和 (或) 適合某特定用途之默示擔保。 本文中討論的 Visual Basic 程序,僅適用於「現有狀況」,Microsoft 不保證適用於所有的情況。 Microsoft 支援工程師可以協助說明特定巨集的功能,但無法修改這些範例以提供附加功能或建構巨集來滿足您的特定需求。 如果您的程式設計經驗有限,則可能需要諮詢某位 Microsoft 解決方案供應商。 解決方案供應商提供廣泛的收費服務,包括創建自訂巨集。 有關 Microsoft 解決方案供應商的詳細資訊,請致電 Microsoft 客戶資訊服務 (800) 426-9400。

範例

  1. 在新模組中輸入下列程式碼:

        ' Makes sure all variables are dimensioned in each subroutine.
    Option Explicit

    ' Access the GetUserNameA function in advapi32.dll and
    ' call the function GetUserName.
    Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" _
    (ByVal lpBuffer As String, nSize As Long) As Long

    ' Main routine to Dimension variables, retrieve user name
    ' and display answer.
    Sub Get_User_Name()

    ' Dimension variables
    Dim lpBuff As String * 25
    Dim ret As Long, UserName As String

    ' Get the user name minus any trailing spaces found in the name.
    ret = GetUserName(lpBuff, 25)
    UserName = Left(lpBuff, InStr(lpBuff, Chr(0)) - 1)

    ' Display the User Name
    MsgBox UserName
    End Sub
  2. 執行巨集 Get_User_Name。 請注意,當前使用者名稱將顯示在訊息方塊中。

Need more help?

Want more options?

探索訂閱權益、瀏覽訓練課程、瞭解如何保護您的裝置等等。

社群可協助您詢問並回答問題、提供意見反應,以及聆聽來自具有豐富知識的專家意見。

Was this information helpful?

How satisfied are you with the translation quality?
What affected your experience?
By pressing submit, your feedback will be used to improve Microsoft products and services. Your IT admin will be able to collect this data. Privacy Statement.

Thank you for your feedback!

×