首页 > 解决方案 > 如何使用此 vba 代码添加其他 mac 地址?

问题描述

我的vba是

    Public Function notmacaddress()

    Dim m As String
    Const test = "11:11:11:11:11:11"
    
    m = GetMACAddress
    
    If m <> test Then
        notmacaddress = True
    Else
        notmacaddress = False
    End If
    
    End Function

    Function GetMACAddress() As String
        Dim sComputer As String
        Dim oWMIService As Object
        Dim cItems As Object
        Dim oItem As Object
        Dim myMacAddress As String
    
        sComputer = "."
    
        Set oWMIService = GetObject("winmgmts:\\" & sComputer & "\root\cimv2")
    
        Set cItems = oWMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
    
        For Each oItem In cItems
            If Not IsNull(oItem.IPAddress) Then myMacAddress = oItem.macAddress
            Exit For
        Next
        'it will return mac address in format MM:MM:MM:SS:SS:SS
        GetMACAddress = myMacAddress
    End Function
    
    Private Sub Workbook_Open()
       If notmacaddress Then
          ThisWorkbook.Close
       End If
    End Sub

如何在代码中添加其他mac地址???例如: "11:11:11:11:11:11" "22:22:34:32:55:23" "34:45:45:33:33:11"

Excel 只是在 mac 地址系统中运行。

标签: excelvba

解决方案


请尝试下一个改编的功能:

Public Function notMACAddress() As Boolean
    Dim m As String, arrMAC As Variant, El As Variant
    Const test = "11:11:11:11:11:11,22:22:34:32:55:23,34:45:45:33:33:11"
    'add above the MAC string you need to be checked (separated by comma)
    
    arrMAC = Split(test, ",")
    m = GetMACAddress
    
    For Each El In arrMAC
        If m = El Then
            notMACAddress = False: Exit Function
        End If
    Next El
    notMACAddress = True
End Function

可以这样测试:

Sub checkMACAddress()
    Debug.Print GetMACAddress
    Debug.Print notMACAddress
End Sub

它允许添加多少个 MAC 地址,用逗号分隔,你需要。

您可以通过以下方式使用该功能:

Private Sub Workbook_Open()
    If notMACAddress Then ThisWorkbook.Close
End If

但是,如果工作簿在禁用宏的情况下打开...


推荐阅读