gpt4 book ai didi

Excel VBA 检查 InStr 函数中的值

转载 作者:行者123 更新时间:2023-12-04 21:06:35 24 4
gpt4 key购买 nike

我的情况

我编写此代码的主要原因是检查 IP 地址是内部连接还是外部连接。

我的数据表中的一个单元格不仅包含 IP 地址值,还可以包含其他类型的文本。 F.e. :

“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”。眼下。

提前致谢

最佳答案

您可以/应该将该测试分解为它自己的功能。这是一个仅解析字符串的示例。

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

关于Excel VBA 检查 InStr 函数中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15132893/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com