如何将一个字符串与许多其他字符串进行比较?

时间:2019-07-08 22:21:36

标签: excel vba

我正在尝试比较两个名称列表,并找到两个列表中的名称。但是,列表的顺序不同,长度也不同。

我尝试了一个代码,将第一个列表的名称(“ A1”)与另一个列表中的第一个名称(“ B1”)进行比较,然后将其与第二个列表(“ B3”)进行比较,依此类推,直到它匹配。如果匹配,则在第三列上写“匹配”,如果没有匹配,则写“不匹配”

Sub CompareTest()
    Dim iComp As Integer, i As Integer, j As Integer
    Dim str1 As string, str2 As string

    For i = 1 to 20
        str1 = ("A" & i)

        For j = 1 to 20
            str2 = ("B" & j)
            iComp = StrComp(str1, str2, vbTextCompare)

            Select Case iComp
            Case 0
                Range ("C" & i) = "Match"
            Case 1
                Range ("C" & i) = "Match"
            End Select

            If Range ("C" & i) = "Match" Then Exit For
        Next j
    Next i
End Sub

现在,即使有匹配项,代码也会在1到20的每个单元格中写入“ Not a match”(不匹配),我不确定什么是行不通的。

1 个答案:

答案 0 :(得分:0)

在您的代码中,您将比较字符串"An""Bn",而不是地址的内容。但是即使您纠正了该错误,但如果str1等于或大于 str2,您仍在写“匹配”。可能不是您想要的。

您可能可以执行以下操作:

C1:  =IF(COUNTIF(B:B,A1),"Match","Not a Match")

或者,在代码中

Option Explicit
Sub matcher()
    Dim WS As Worksheet
    Dim C As Range, rSearch As Range, rLookup As Range

Set WS = Worksheets("sheet2")
With WS
    Set rLookup = .Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp))
    Set rSearch = .Range(.Cells(1, 2), .Cells(.Rows.Count, 2).End(xlUp))
    .Columns(3).Clear
End With


For Each C In rLookup
    If rSearch.Find(what:=C, LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False) Is Nothing Then
        C.Offset(0, 2) = "No Match"
    Else
        C.Offset(0, 2) = "Match"
    End If
Next C

End Sub