VBA Get Username on OSX (or Mac alternative to Env

2019-01-28 10:19发布

问题:

My task has been to create a secure (Windows version) Excel workbook that uses macros to validate whether a user has permission to view the contents. In Excel 2010 for Windows, I use the Environ("username") function to accomplish this.

The problem I'm running into is that some users in the organization use a Mac to do their daily work, and Environ does not work with OSX.

Does anyone know of an alternate way to find the username of a Mac? I've looked online but all I can find is how to find the unique identifier of the computer, not the username.

Is what I'm attempting to do even possible with Mac?

Any information is appreciated!

回答1:

You can use AppleScript to return the Username and run that from VBA.

The following function should do the trick.

Function GetUserNameMac() As String
    Dim sMyScript As String

    sMyScript = "set userName to short user name of (system info)" & vbNewLine & "return userName"

    GetUserNameMac = MacScript(sMyScript)
End Function


回答2:

Environ("USER") and Environ("LOGNAME") return the same thing on the Mac as the MacScript answer.