我正在尝试验证其中一列中是否存在数字(7)或字符串('7'),以及是否返回消息框。例如,请考虑以下数据:
Name Cod
A 7
A 3
B 4
C 7;3
D 7 3
D 7, 3
F 7 - 3
F 5
我可以在Cod列中找到数字7,但无法检查它与其他数字和符号(如逗号,短划线,分号等)何时结合使用。以下代码适用于单元格B2:
Dim N As Range
Sub Find_7_string()
msg = ""
For Each N In Range("A2", Range("A2").End(xlDown))
If N.Offset(, 1) = 7 Then
msg = msg & "There should not be 7 in column Cod" & vbLf
Exit For
End If
Next N
If Len(msg) > 1 Then
MsgBox msg
End If
End Sub
但它对细胞B5,B6,B7和B8不起作用。
如果字符'7'是与其他字符一起输入的字符串,我怎么能验证它?
答案 0 :(得分:2)
您可以使用Instr
功能,如下所示:
Sub Find_7_string()
Dim N As Range
Dim msg As String
msg = ""
For Each N In Range("A2", Range("A2").End(xlDown))
If InStr(N.Offset(, 1), 7) Then
msg = msg & "There should not be 7 in column Cod" & vbLf
Exit For
End If
Next N
If Len(msg) > 1 Then
MsgBox msg
End If
End Sub
注意,也会找到77,7,382等
答案 1 :(得分:1)
手册
7
Or
等于 7
VBA
Sub Findem()
Dim rng1 As Range
ActiveSheet.AutoFilterMode = False
Set rng1 = Range([b1], Cells(Rows.Count, "B").End(xlUp))
rng1.AutoFilter Field:=1, Criteria1:="=*7*", Operator:=xlOr, Criteria2:="=7"
End Sub