我需要一个验证单元格值的宏。它需要检查值是否为7个字母和6个数字(passwds123456)。字母总是相同但不是最后的6个数字。
我希望我足够清楚。这是我目前的代码:
Private Sub CommandButton15_Click()
Dim i As Integer
If Len(Range("H3").Value) <> 13 Then
MsgBox "ok lenght is not 13"
End If
For i = 8 To 13
If IsNumeric(i) = True Then
MsgBox "6 last are numbers"
End If
Next i
End Sub
但是这没有正确检测数字部分。
我错过了什么?
答案 0 :(得分:4)
不是测试每个字符以查看它是否为数字,而是使用Right
将最后6个字符作为单个字符串进行测试(使用IsNumeric
):
Option Explicit
Sub test()
If Len(Range("H3").Value) <> 13 Then
MsgBox "ok length is not 13"
Else
If IsNumeric(Right(Range("H3").Value, 6)) = True Then
MsgBox "6 last are numbers"
End If
End If
End Sub
要展开,如果您在H3中的值为&#34; passwds123456&#34;,Right(Range("H3").Value, 6)
将返回&#34; 123456&#34;,然后会针对IsNumeric
返回True
修改强>
正如@ YowE3K指出的那样,另一种符号中的数字可以通过这个测试,所以一个更清晰的解决方案(还有更多)将分别测试每个字符:
Option Explicit
Sub test()
Dim i As Integer, flag As Boolean
If Len(Range("H3").Value) <> 13 Then
MsgBox "ok length is not 13"
Else
For i = 0 To 5
If Not IsNumeric(Mid(Range("H3").Value, 8 + i, 1)) = True Then
flag = True
End If
Next i
If flag = False Then
MsgBox "6 last are numbers"
End If
End If
End Sub