VBA使用带有通配符的like运算符

时间:2016-05-24 23:30:48

标签: excel vba excel-vba

我试图比较地址数据。我当前的宏比较了两列和输入" Dropped Data"当他们不匹配时。问题是大量的这些价值观没有被淘汰,而是被整合到另一个细胞中。我想更改我的宏,以便能够使用VBA&like运算符找到缺失的值。例如,它会找到" Bldg 3" in" 9825 Spectrum Dr Bldg 3"。我能够通过浏览网页来获取此代码,并且我不确定Range("C65536")选择的范围。

编辑:我看到人们建议我使用Instr功能,这似乎做了我想做的事情。我不确定如何让它在我的宏中工作/让它引用正确的单元格。它(根据我的理解)返回的值等于找到的字符数。因此,在我给出的示例中,如果包含空格,则返回值6。

Sub droppeddata()

Application.ScreenUpdating = False

lr = Range("C65536").End(xlUp).Row
For a = lr To 1 Step -1
If Not IsEmpty(Cells(a, 13).Value) And IsEmpty(Cells(a, 19)) Then
Cells(a, 10).Select
Selection.NumberFormat = "General"
    ActiveCell.FormulaR1C1 = "N"
Cells(a, 11).Select
Selection.NumberFormat = "General"
    ActiveCell.FormulaR1C1 = "Dropped Data"
End If
Next a

Application.ScreenUpdating = True
End Sub

1 个答案:

答案 0 :(得分:1)

您当前的宏没有按照您希望的方式进行比较,只是检查两列是否为空。

你还没有对你要做的事情非常具体,所以这段代码是通过一些猜测来完成的:

Sub droppeddata()
    Dim lr As Long ' Declare the variable
    lr = Range("C65536").End(xlUp).Row ' Set the variable
    ' lr now contains the last used row in column C

    Application.ScreenUpdating = False

    For a = lr To 1 Step -1
        If IsEmpty(Cells(a, 19)) Or InStr(1, Cells(a, 13).Value, Cells(a, 19).Value, vbTextCompare) > 0 Then
        ' If Cells(a, 19) is empty OR
        ' Search Cells(a, 13) for the value contained in Cells(a, 19)
        ' If INSTR returns a match greater than 0, it means the string we're looking for is present
        ' Enter the loop if either condition is true

            ' In this section, avoiding SELECT is preferable. Working directly on the ranges is good.
            With Cells(a, 10)
                .NumberFormat = "General"
                .Value = "N"
            End With

            With Cells(a, 11)
                .NumberFormat = "General"
                .Value = "Dropped Data"
            End With
        End If
    Next a

    Application.ScreenUpdating = True
End Sub

根据您的需要更改范围/单元格 - 当前的单元格/单元格无法正常工作,我只是根据您现有的代码猜测。