การตรวจสอบหมายเลข IP ว่าอยู่ใน Range ใดหรือไม่

Smile สำหรับหมายเลข IP ซึ่งต้องมองทีละชุดไปนั้นไม่สามารถใช้การตรวจสอบได้เหมือนเลขธรรมดา ต้องตรวจสอบหมายเลขเป็นชุด ๆ ไป การตรวจสอบด้วยสูตรจึงทำได้ลำบากแต่สามารถใช้ VBA เข้ามาช่วยได้ครับ

สำหรับตัวอย่าง Code ตามด้านล่างจะเป็นการนำ I3:I17 ไปตรวจสอบกับ C3:D7

ว่าอยู่ในช่วงใดหรือไม่ หากพบว่าอยู่ในช่วงใดจะเติมค่า Y ในคอลัมน์ J หากไม่พบจะเติมค่า N

🖼️ ภาพประกอบการตรวจสอบ IP

CheckIPInterval
ภาพ 1 การตรวจสอบ IP

เราสามารถใช้ Code VBA ตามด้านล่างครับ

Sub CheckIPRange()
Dim r As Range, rAll As Range
Dim rt As Range, rtAll As Range
Dim ipParts As Variant, startParts As Variant, endParts As Variant
Dim isInRange As Boolean
Dim ws As Worksheet
Set ws = Sheets("Sheet1")

' กำหนดช่วงข้อมูล IP ที่ต้องตรวจสอบ
Set rAll = ws.Range("I3", ws.Cells(ws.Rows.Count, "I").End(xlUp))
Set rtAll = ws.Range("C3", ws.Cells(ws.Rows.Count, "C").End(xlUp))

For Each r In rAll
isInRange = False
ipParts = Split(Trim(r.Value), ".")

If UBound(ipParts) = 3 Then
For Each rt In rtAll
startParts = Split(Trim(rt.Value), ".")
endParts = Split(Trim(rt.Offset(0, 1).Value), ".")

If UBound(startParts) = 3 And UBound(endParts) = 3 Then
If CompareIP(ipParts, startParts) >= 0 And CompareIP(ipParts, endParts) <= 0 Then
r.Offset(0, 1).Value = "Y"
isInRange = True
Exit For
End If
End If
Next rt
End If

If Not isInRange Then r.Offset(0, 1).Value = "N"
Next r
End Sub

Function CompareIP(ip1 As Variant, ip2 As Variant) As Long
Dim i As Integer
For i = 0 To 3
If Val(ip1(i)) < Val(ip2(i)) Then
CompareIP = -1: Exit Function
ElseIf Val(ip1(i)) > Val(ip2(i)) Then
CompareIP = 1: Exit Function
End If
Next i
CompareIP = 0
End Function

Revised: January 29, 2017 at 07:56

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top