VBA Run-time error 1004 FormulaR1C1 Index Match using String variables for sheet names

Viewed 18

I'm trying to make a macro with a dynamic index match, the worksheet names change which is why I'm using variables for that as well as the ranges. When I run the code it give me a 1004 run-time error (the line responsible is the index match line) but I don't know why as the syntax seems fine and if remove the equal sign before index, run the macro, change RC[-10] to a the cell (AA2) and then put the equal sign manually in the sheet it works fine. Below is my code, thanks in advance!

 Sub Compare_Results()

    'Create variables
    Dim BOCurrWeek As String
    Dim BOPrevWeek As String
    Dim lastRow As Long
    Dim myRange1 As String
    Dim myRange2 As String
    
    Worksheets("Update Me").Activate
    'Activate Back office sheet
    Worksheets(BOCurrWeek).Activate
    
    'Name new columns
    Range("AK1").Select
    ActiveCell.FormulaR1C1 = "Prev OS"
    Range("AL1").Select
    
    'Get sheet names
    BOPrevWeekN = Range("B4").Value
    BOCurrWeek = Range("B8").Value
 
    'Get number of rows for previous week of Back office data
    Worksheets(BOPrevWeek).Activate
    lastRow = Cells(ActiveSheet.Rows.Count, 1).End(xlUp).Row
    'Debug.Print lastRow
    
    'Set Prev Os formula
    myRange1 = "$T$1:$T$" & lastRow
    myRange2 = "$AA$1:$AA$" & lastRow
    
    Worksheets(BOCurrWeek).Activate

    Range("AK2").Select
    'Gives error
    ActiveCell.FormulaR1C1 = _
        "=Index('" & BOPrevWeek & "'!" & myRange1 & ",Match(AA2,'" & BOPrevWeek & "'!" & myRange2 & ",0),0)"
              
End Sub
0 Answers
Related