摘要
您可以到 Microsoft Windows DLL (动态链接库) 的 Windows API (应用编程接口) 调用来获取当前的用户名称。可以通过在 ADVAPI32 中使用 GetUserNameA 函数获取当前用户名。DLL 中。
更多信息
Microsoft Excel 没有内置的功能,用于访问计算机的当前用户的名称。但是,可以在 Visual Basic for Applications 宏使用 Declare 语句来调用的 Windows 函数,将返回当前用户名。Microsoft 提供的 Visual Basic for Applications 过程的示例仅用于说明,而不附带任何明示或暗示的担保,包括但不是限于适销性和针对特定用途的适用性的暗示担保。这篇文章中的 Visual Basic 过程按原样提供,Microsoft 不能保证可以在所有情况下使用它们。虽然 Microsoft 支持专业人员可以帮助解释某个宏的功能,他们不会修改这些示例以提供附加的功能,也不他们将帮助您构建宏以满足您的特定需求。如果您的编程经验有限,您可能需要参考 Microsoft 解决方案供应商之一。解决方案提供商提供范围广泛的收费服务,包括创建自定义的宏。有关 Microsoft 解决方案提供商的详细信息,调用 (800) 426-9400 Microsoft 客户信息服务。
示例
-
到新模块中键入以下代码:
' 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
-
运行该宏 Get_User_Name。请注意,当前的用户名称将显示在消息框中。