excel - 查找与其他字符一起输入的特定字符串

标签 excel vba

我正在尝试验证其中一列中是否存在数字 (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”是与其他字符一起输入的字符串时,我如何验证它?

最佳答案

您可以使用 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 等。

关于excel - 查找与其他字符一起输入的特定字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24891186/

相关文章:

excel - 在 Excel 中使用 VBA 编写宏

vba - 运行时错误 '1004' 'Range' of object'_Global' 失败

excel - 如何从作为所选单元格内容的名称列表创建多个工作表

vba - Excel VBA - VBA 内的日期和 IF 函数给出错误

vba - Excel VBA ClearContents 错误

Excel:如何使用通配符替换文本?

swift - 在 Swift Xcode 中使用 Excel 工作表中的数据

excel - VLOOKUP 产生错误的数字

loops - Else If 是否为 FileExists()

vba - 用户表单初始化后更新用户表单列表框