一个关于IP输入合法性的判断语句,请高手帮忙看看。运行出错。。
代码如下:
Private Sub Command1_Click()
Dim Str1, Str2, Str3, Str4 As String
Dim s1, s2, s3, s4 As Integer
s1 = InStr(Text1.Text, ".") '获取小数点的位置
If s1 = 0 Then
MsgBox "输入地址不合法!请从新输入"
Str1 = Left(Text1.Text, s1 - 1) '截取小数点前面的字符
If Int(Str1) > 255 Or Int(Str1) < 0 Then '把字符换成整型做比较
MsgBox "输入地址不合法!请从新输入"
Else
s2 = InStr(Right(Text1.Text, Len(Text1.Text) - s1), ".") '获取从上一个小数点后下一个小数点的位置
If s2 = 0 Then
MsgBox "输入地址不合法!请从新输入"
Str2 = Left(Right(Text1.Text, Len(Text1.Text) - s1), s2 - 1) '截取从上一个小数点后下一个小数点前的字符
If Int(Str2) > 255 Or Int(Str2) < 0 Then
MsgBox "输入地址不合法!请从新输入"
Else
s3 = InStr(Right(Text1.Text, Len(Text1.Text) - s1 - s2), ".")
If s3 = 0 Then
MsgBox "输入地址不合法!请从新输入"
Str3 = Left(Right(Text1.Text, Len(Text1.Text) - s1 - s2), s3 - 1)
If Int(Str3) > 255 Or Int(Str3) < 0 Then
MsgBox "输入地址不合法!请从新输入"
Else
s4 = InStr(Right(Text1.Text, Len(Text1.Text) - s1 - s2 - s3), ".")
If s4 = 0 Then
MsgBox "输入地址不合法!请从新输入"
Str4 = Left(Right(Text1.Text, Len(Text1.Text) - s1 - s2 - s3), s4 - 1)
If Int(Str4) > 255 Or Int(Str4) < 0 Then
MsgBox "输入地址不合法!请从新输入"
Else
MsgBox "输入的地址合法!"
End If
Else
MsgBox "输入地址不合法!请从新输入"
End If
End If
End If
End If
End Sub
[解决办法]
给你改了下
Private Sub Command1_Click()Dim TmpA, i As ByteTmpA = Split(Text1.Text, ".")On Error GoTo ErrEIf UBound(TmpA) <> 3 Then GoTo ErrEFor i = 0 To 3 If Int(TmpA(i)) > 255 Or Int(TmpA(i)) < 0 Then GoTo ErrENextExit SubErrE: MsgBox "输入地址不合法!请从新输入"End Sub
[解决办法]
有那么复杂吗?
Function ChkIp(ip As String) As Boolean Dim nrs() As String ChkIp = False If Len(Replace(ip, ".", "")) = (Len(ip) - 3) Then nrs = Split(ip, ".") If nrs(0) >= 256 Or nrs(1) >= 256 Or nrs(2) >= 256 Or nrs(3) >= 256 Then ChkIp = False Exit Function End If Else ChkIp = False Exit Function End If ChkIp = TrueEnd Function
[解决办法]
Option ExplicitFunction CheckIP(pStr As String) As Boolean Dim tOutBool As Boolean Dim tStringNums() As String Dim tStringNums_Length As Long Dim tStringNums_Index As Long Dim tIPNum As Long tStringNums() = Split(pStr, ".") tStringNums_Length = UBound(tStringNums()) tOutBool = tStringNums_Length = 3 If tOutBool Then For tStringNums_Index = 0 To tStringNums_Length tOutBool = tOutBool And IsNumeric(tStringNums(tStringNums_Index)) If tOutBool Then tIPNum = CLng(tStringNums(tStringNums_Index)) tOutBool = tOutBool And (tIPNum >= 0) And (tIPNum <= 255) Else Exit For End If Next End If CheckIP = tOutBoolEnd FunctionPrivate Sub Text1_Change() Command1.Caption = CheckIP(Text1.Text) Command1.Enabled = CheckIP(Text1.Text)End Sub
[解决办法]
Dim Text As String, IPStr As Variant, IP(3) As Byte, i As IntegerText = "192.168.1.1"IPStr = Split(Text, ".", 4)For i = 0 To 3 If Val(IPStr(i)) >= 0 And Val(IPStr(i)) <= 255 Then IP(i) = IPStr(i) Else MsgBox "输入地址不合法!请从新输入" Exit For End IfNext