Excel VBA检查InStr函数中的值

我的情况

我做这个代码的主要原因是检查一个IP地址是一个实习生还是外部连接。

我的数据表中的单元格不仅包含IP地址值,还可以包含其他types的文本。 Fe:

“BE-ABCDDD-DDS 172.16.23.3”

我的问题

我想检查一个单元格是否在“172.31”之间包含“172.16”的IP地址。在上面的例子中,它将返回一个值true / Intern。 如果单元格的值为“172.32”,则返回false / extern。

这是我的代码:

For Each source In Range("E6", Range("E" & Rows.Count).End(xlUp)) If (InStr(source, "-10.") <> 0 Or InStr(source, "-192.168.") <> 0 Or InStr(source, "- 172.") <> 0) And InStr(source.Offset(0, 22).Value, "Extern") = 0 Then source.Offset(0, 22) = "Intern" End If Next source 

正如你在我的代码中看到的,它只能检查“172”。 在这一刻。

提前致谢

你可以/应该把这个testing分解成它自己的function。 这里只是一个parsingstring的例子。

 Sub Main() Dim rCell As Range For Each rCell In Sheet1.Range("A1:A5").Cells If IsInternal(rCell.Value) Then Debug.Print rCell.Address, rCell.Value End If Next rCell End Sub Public Function IsInternal(sIpAdd As String) As Boolean Dim bReturn As Boolean Dim lIpStart As Long Dim lSecQuad As Long Const sIPSTART As String = "172." Const lMIN As Long = 16 Const lMAX As Long = 31 'Default to false unless we explictly set it to true bReturn = False 'See if 172. exists in the string lIpStart = InStr(1, sIpAdd, sIPSTART) 'If 172. exists If lIpStart > 0 Then 'Parse out the second quadrant lSecQuad = Val(Mid(sIpAdd, lIpStart + Len(sIPSTART), 2)) 'See if the second quadrant is in range 'and set to true if so bReturn = lSecQuad >= lMIN And lSecQuad <= lMAX End If IsInternal = bReturn End Function 

我强烈build议这个正则expression式。 如果您使用的是VBA,则可以参考VBA项目中的Microsoft VBScript正则expression式库。

一旦你有了引用,你可以使用一个正则expression式来search给定的匹配模式的string。 下面是一个“可能有效的IPstring”示例VBScript正则expression式友好的expression式:\ d {1,3}。\ d {1,3}。\ d {1,3}。\ d {1,3}

这将匹配一个string,它有一个4位,1-3位的数字序列,其中包含句点,比如127.0.0.1,但也可能是955.556.234.234。 所以,一旦你有一个匹配的string,我会validation代码中的IP组件,然后再考虑IP“有效”。 一旦你有一个有效的IP,它应该是一个快速检查你的情况。

希望这可以帮助!