简体   繁体   中英

Comparing two columns - New to VBA

I'm new to Excel VBA and I want to compare the cells (strings) of two columns and check if:

  • There is some cells with "two" matching words
  • There is some cells which begin by the same word

My code returns an error and I can't figure it out, someone can help me with this please!

Sub Find_Matches()
   Dim CompareRange As Variant, x As Variant, y As Variant, mot As Variant, mot2 As Variant, compt As Variant, element As Variant, element2 As Variant

    compt = 0   'counter for number of matching words
    Set CompareRange = Range("C1:C1796")   'first column

    For Each x In Selection   'second column
        For Each y In CompareRange

             mot = Split(x, " ")   'converting strings to words arrays
             mot2 = Split(y, " ")

             For Each element In mot
               For Each element2 In mot2

                  If element = element2 Then compt = compt + 1   'matching words counter incrementation

               Next element2
             Next element

            If compt >= 2 Or mot(0) = mot2(0) Then ....   'if/or then do something
            compt = 0

        Next y
    Next x
  End Sub

When I debug, the highlighted text is : "If compt >= 2 Or mot(0) = mot2(0)". The error translated since I'm using a french version is: " Execution error '9': The index doesn't belong to the selection ".

UPDATE1: I Still have the same error even if the cells are not empty, same error on same line:

   For Each x In Selection
        For Each y In CompareRange

        If CStr(x) & CStr(y) <> vbNullString Then
             mot = Split(x, " ")
             mot2 = Split(y, " ")
        Else: MsgBox "empty cell!"
        End If

             For Each element In mot
             For Each element2 In mot2
             If element = element2 Then compt = compt + 1
            Next element2
            Next element
            If compt >= 2 Or mot(0) = mot2(0) Then x.Offset(0, 1) = x
            compt = 0
        Next y
    Next x

Try this, and hope there is no more than 2 consecutive spaces :), write it before the splits

x = Trim(Replace(x, "  ", " "))
y = Trim(Replace(y, "  ", " "))

Use this function to remove unneeded spaces:

Function RemoveSpaces(ByVal s As String) As String
Dim a As Integer, b As Integer
s = Trim(s)
Do
 a = Len(s)
 s = Replace(s, "  ", " ")
 b = Len(s)
Loop Until a = b
RemoveSpaces = s
End Function

Now in your sub use x = RemoveSpaces(x)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM