Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Column comparison error in VBA

Tags:

excel

vba

Hello I am writing a macro that compares two columns on different sheets in excel. The macro is as follows:

Sub Main()
Application.ScreenUpdating = False

    Dim stNow As Date
    stNow = Now

    Dim arr As Variant
    arr = Worksheets("Sheet2").Range("W3:W" & Range("W" & Rows.Count).End(xlUp).Row).Value

    Dim varr As Variant
    varr = Worksheets("Sheet3").Range("P3:P" & Range("P" & Rows.Count).End(xlUp).Row).Value

    Dim x, y, match As Boolean
    For Each x In arr
        match = False
        For Each y In varr
            If x = y Then match = True
        Next y
        If Not match Then
            Worksheets("Sheet1").Range("L" & Range("L" & Rows.Count).End(xlUp).Row + 1) = x
        End If
    Next

    Debug.Print DateDiff("s", stNow, Now)
Application.ScreenUpdating = True
End Sub

If the colums are on the same sheets and there are no sheet references in the code, it works perfectly. But now it only copies the first cell from Sheet3 column W, altough this value already exists in the column in P on Sheet3.

like image 240
tombata Avatar asked Mar 23 '26 15:03

tombata


1 Answers

As you notice, when there are no sheet references, it works fine.

You need to always qualify Range(), Rows. and Columns., otherwise it'll use whatever the ActiveSheet is.

The following should work for you.

Sub Main()
Application.ScreenUpdating = False

Dim stNow   As Date
stNow = Now

Dim arr     As Variant
With Worksheets("Sheet2")
    arr = .Range("W3:W" & .Range("W" & .Rows.Count).End(xlUp).Row).Value
End With

Dim varr    As Variant
With Worksheets("Sheet3")
    varr = .Range("P3:P" & .Range("P" & .Rows.Count).End(xlUp).Row).Value
End With

Dim x, y, match As Boolean
For Each x In arr
    match = False
    For Each y In varr
        If x = y Then
            match = True
            Exit For
        End If
    Next y
    If Not match Then
        With Worksheets("Sheet1")
            .Range("L" & .Range("L" & .Rows.Count).End(xlUp).Row + 1) = x
        End With
    End If
Next

Debug.Print DateDiff("s", stNow, Now)
Application.ScreenUpdating = True
End Sub

Note: I added With statements to cut down on the repetitiveness of using Worksheets("Sheetx"). Also, updated the If x = y statement, per @ScottCraner's comment.

Also I see that you have a few undeclared variables. I recommend adding Option Explicit to the very start (before Sub Main()) and declare all variables.

like image 197
BruceWayne Avatar answered Mar 26 '26 15:03

BruceWayne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!