如何检查用户的操作系统,然后相应地包含库

时间:2015-07-30 22:59:35

标签: windows excel macos vba

我目前正在尝试创建一个包含特定API库的简单VBA代码,当且仅当用户运行的是Windows而不是Mac时。

原因是因为如果用户正在运行Mac,则代码不起作用,因为我使用的是Windows API库。

我需要做的是检查用户是否正在运行Mac和SKIP,包括库,否则如果用户正在运行Windows,则包含该文件。

以下是我目前在VBA中的代码: http://pastebin.com/fhuiumwk

'check if the OS is Windows
#If Not Mac Then
'get the correct API for Windows
Private Declare PtrSafe Function Get_User_Name Lib "advapi32.dll" _
  Alias "GetUserNameA" (ByVal lpBuffer As String, nSize _
  As Long) As Long

'function declaration for getting the Window user (dependent on the above API)
Function ExtractWindowsUser() As String
    'variables
   Dim stringBuffer As String * 100
    Dim longBufferLength As Long

    'set variables
   longBufferLength = 100
    Get_User_Name stringBuffer, longBufferLength

    'get the user's name
   ExtractWindowsUser = Left(stringBuffer, longBufferLength - 1)
End Function

'end OS check
#End If

'pre-built "function" that analyzes changes in cells
Private Sub Worksheet_Change(ByVal Target As Range)

    'check OS (because I don't want to do anything if the user is running Mac)
   If Not Mac Then

        'utilizes active sheet being looked at
       With ActiveSheet

            'monitors the D column for a change
           If Not Application.Intersect(Target, .Range("B:B")) Is Nothing Then

                'inserts custom function (defined above) into the desired column of current row
               .Cells(Target.Row, 4) = ExtractWindowsUser()

                'inserts NOW function to desired column of current row
               .Cells(Target.Row, 3) = Format(Now(), "YYYY-MM-DD")

            'end if for intersection
           End If

        'end sheet
       End With

    'end OS check
   End If

    'If not windows do nothing

'end sub for checking change
End Sub

澄清一下 - 这段代码在Excel上的Windows上运行就好了。但是一旦我尝试从Mac访问它,它显然不能包含API和崩溃。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

您错过了#支票中的If Not Mac

'check OS (because I don't want to do anything if the user is running Mac)
#If Not Mac Then

    'utilizes active sheet being looked at
   With ActiveSheet

        'monitors the D column for a change
       If Not Application.Intersect(Target, .Range("B:B")) Is Nothing Then

            'inserts custom function (defined above) into the desired column of current row
           .Cells(Target.Row, 4) = ExtractWindowsUser()

            'inserts NOW function to desired column of current row
           .Cells(Target.Row, 3) = Format(Now(), "YYYY-MM-DD")

        'end if for intersection
       End If

    'end sheet
   End With

  'end OS check
 #End If

Re:"没有使用'不是'在条件编译指令" -

#Const NUM = False

Sub TestMe()
    #If Not NUM Then
        Debug.Print "Not NUM!"  '<<prints
    #Else
        Debug.Print "NUM!"      '<<doesn't print
    #End If
End Sub