0

I try to select the range that was union under one variable, but it fails.

Sub filter()
    'Clear prev result table
    Worksheets("main").Range("A3").CurrentRegion.Delete

    'Declare variable
    Dim selectedRows As Range
    Set selectedRows = Worksheets("contacts").Range("A1:B1")


    'Get total used range in contacts database
    numRows = Mid(Worksheets("contacts").UsedRange.Address, 9)
    For Each cell In Worksheets("contacts").Range("B1:B" & numRows)
        If cell.Value = Worksheets("main").Range("B1").Value Then
            'If true, push into array called selectedRows
            Set selectedRows = Application.Union(selectedRows, Worksheets("contacts").Range(cell.Address))
        End If
    Next

    selectedRows.Select '<------ fail here
    Copy Worksheets("main").Range("A3")
End Sub

The macro failed and error message said: Select method or Range class failed. What is wrong with my code?

braX
  • 11,506
  • 5
  • 20
  • 33
  • You should test if `selectedRows = Nothing` before Selecting. Also, is `Worksheets("contacts")` hidden by any chance? One more thought try starting with `Set selectedRows = Worksheets("contacts").Range("A1")` as you test `B1` in your loop and not sure if you can have it in your selected range twice. – Tom Nov 21 '18 at 09:16
  • Without too much testing the code worked for me - except that last line which should be `Worksheets("main").Range("A3").Copy`. **Edit:** But I did have the correct sheet selected - the code given by @PawelCzyz should work. – Darren Bartrup-Cook Nov 21 '18 at 09:43

1 Answers1

1

You get the error msg because sheet "contacts" is not active. Add this line:

Worksheets("contacts").Activate

Like this:

Sub filter()
    'Clear prev result table
    Worksheets("main").Range("A3").CurrentRegion.Delete

    'Declare variable
    Dim selectedRows As Range
    Set selectedRows = Worksheets("contacts").Range("A1:B1")


    'Get total used range in contacts database
    numRows = Mid(Worksheets("contacts").UsedRange.Address, 9)
    For Each cell In Worksheets("contacts").Range("B1:B" & numRows)
        If cell.Value = Worksheets("main").Range("B1").Value Then
            'If true, push into array called selectedRows
            Set selectedRows = Application.Union(selectedRows, Worksheets("contacts").Range(cell.Address))
        End If
    Next

    Worksheets("contacts").Activate

    selectedRows.Select '<------ fail here

    'this line below is incorrect
    'Copy Worksheets("main").Range("A3")
End Sub

I recommend reading this post: How to avoid using Select in Excel VBA - it will help you improve your code.

JohnyL
  • 6,894
  • 3
  • 22
  • 41
Pawel Czyz
  • 1,651
  • 4
  • 17
  • 21