Excel VB /宏InStr精确搜索

时间:2018-05-11 23:48:39

标签: excel vba excel-vba

我需要能在Excel中搜索列的内容,并在搜索匹配时输出内容。大部分都有效,但类似的值似乎不起作用。例如:

Sub ConvertComputerNames()

Dim SrchRng As Range, cel As Range

Set SrchRng = Range("A2:A200")

For Each cel In SrchRng
    If InStr(1, cel.Value, "W7ADH") Then
        cel.Offset(0, 7).Value = "LTW7ADH"
    End If
    If InStr(1, cel.Value, "ADH") Then
        cel.Offset(0, 7).Value = "LTW10ADH"
    End If

 Next cel

End Sub

在这种情况下,两者都将显示LTW10ADH。有没有办法让它显示正确的值?我需要它才能完全匹配。任何帮助将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:1)

如果完全匹配意味着单元格值必须完全匹配给定字符串,那么您不会使用Instr()并只比较单元格内容:< / p>

Sub ConvertComputerNames()

    Dim SrchRng As Range, cel As Range

    Set SrchRng = Range("A2:A200")

    For Each cel In SrchRng
        If cel.Value = "W7ADH" Then
            cel.Offset(0, 7).Value2 = "LTW7ADH"
        End If
        If cel.Value = "ADH" Then
            cel.Offset(0, 7).Value2 = "LTW10ADH"
        End If
    Next

End Sub

在这种情况下,最合适的构造将是If ... ElseIf ... End If

For Each cel In SrchRng
    If cel.Value = "W7ADH" Then
        cel.Offset(0, 7).Value = "LTW7ADH"
    ElseIf cel.Value = "ADH" Then
        cel.Offset(0, 7).Value = "LTW10ADH"
    End If
Next

Select Case ... End Select一个:

For Each cel In SrchRng
    Select Case cel.Value
        Case "W7ADH"
            cel.Offset(0, 7).Value = "LTW7ADH"
        Case "ADH"
            cel.Offset(0, 7).Value = "LTW10ADH"
    End Select
Next

如果您确实需要部分匹配,那么@KenWhite指出了问题,另一种正确处理它的方法是再次通过Select Case构造:

Sub ConvertComputerNames()
    Dim SrchRng As Range, cel As Range

    Set SrchRng = Range("A2:A200")

    For Each cel In SrchRng
        Select Case True
            Case InStr(1, cel.Value, "W7ADH")
                cel.Offset(0, 7).Value = "LTW7ADH"
            Case InStr(1, cel.Value, "ADH")
                cel.Offset(0, 7).Value = "LTW10ADH"
        End Select
    Next
End Sub

在第一个匹配的Case条件下,执行相应的代码,然后代码退出Select Case - End Select块,因此检查的顺序是正确的

答案 1 :(得分:-1)

他们当然可以。您的第二个测试与第一个和第二个选项匹配,因此第二个测试将始终适用。将其更改为If..Else如果相反;如果第一个匹配成功,则第二个匹配将永远不会执行。

Sub ConvertComputerNames()
Dim SrchRng As Range, cel As Range

    Set SrchRng = Range("A2:A200")

    For Each cel In SrchRng
      If InStr(1, cel.Value, "W7ADH") Then
          cel.Offset(0, 7).Value = "LTW7ADH"
      Else If InStr(1, cel.Value, "ADH") Then
          cel.Offset(0, 7).Value = "LTW10ADH"
      End If
    Next cel
End Sub