我必须检查VBA excel,单元格值是否是有效的IPv6地址。 IPv6地址如下所示:
2001:0000:3238:DFE1:0063:0000:0000:FEFB
使用简短形式的IPv6这样的问题:
dec0 :: 0A68:0300
这也是一个有效的IPv6地址。
我该如何妥善处理?
答案 0 :(得分:2)
如果您使用Microsoft VBScript Regular Expressions 5.5,则可以使用此thread中的正则表达式将其合并到VBA中。库(在VB编辑器中使用Tools-> References找到它)。代码如下 - 疯狂的正则表达式!
Option Explicit
Function IsIPv6(ByVal strIn As String) As Boolean
Dim objRegex As New RegExp
Dim strPattern As String
strPattern = "(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|"
strPattern = strPattern & "([0-9a-fA-F]{1,4}:){1,7}:|"
strPattern = strPattern & "([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|"
strPattern = strPattern & "([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|"
strPattern = strPattern & "([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|"
strPattern = strPattern & "([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|"
strPattern = strPattern & "([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|"
strPattern = strPattern & "[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|"
strPattern = strPattern & ":((:[0-9a-fA-F]{1,4}){1,7}|"
strPattern = strPattern & ":)|"
strPattern = strPattern & "fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|"
strPattern = strPattern & "::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|"
strPattern = strPattern & "(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|"
strPattern = strPattern & "1{0,1}[0-9]){0,1}[0-9])|"
strPattern = strPattern & "([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|"
strPattern = strPattern & "(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|"
strPattern = strPattern & "(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))"
objRegex.Pattern = strPattern
IsIPv6 = objRegex.Test(strIn)
End Function
Sub Test()
Debug.Print IsIPv6("2001:0000:3238:DFE1:0063:0000:0000:FEFB")
Debug.Print IsIPv6("dec0::0A68:0300")
Debug.Print IsIPv6("foo")
End Sub
将此代码放在Module
中,然后您可以在Worksheet
中使用此功能:
答案 1 :(得分:0)
你能ping一下地址吗?如果是这样,您可以使用Win32_PingStatus尝试解析IP,这适用于IPv4,v6或甚至只是主机名。像这样:
Function IsValidIP(strHost As String) As Boolean
Dim strQuery As String
strQuery = "select * from Win32_PingStatus where Address = '" & strHost & "'"
Dim colItems As Object
Set colItems = GetObject("winmgmts://./root/cimv2").ExecQuery(strQuery)
IsValidIP = False
Dim objItem As Object
For Each objItem In colItems
If IsObject(objItem) Then
If objItem.PrimaryAddressResolutionStatus = 0 Then
IsValidIP = True
Exit Function
Else
'Could do select case here to handle other return codes.
End If
End If
Next
End Function