Search code examples
vbaloopsreferencematchcell

Looping a Cell Reference in a match function


I'm pretty new to VBA and was wondering why my formula doesnt work?

I'm trying to loop the cells Sheets("Summary").Cells(11 + X, 13) in my match function but it doesn't seem to work. Am I doing something wrong?

Sub Reset()

Dim X As Integer

For X = 0 To 19

Sheets("Summary").Cells(11 + X, 13).Select
Selection.Formula = "=INDEX(YMAX!$A:$W,MATCH(Summary!$J$4&"" ""&Summary!$J$5&""     ""&11,YMAX!$B:$B,0),MATCH(sheets("Summary").cells(11 + x,9),YMAX!$1:$1,0))"

Next X

End Sub

Solution

  • It looks like you have the following errors

    • &'s are in the wrong places (should be outside of the quotes when concatenating text, inside the quotes when concatenating cell references)
    • Variables (i.e. your reference to a cell on the "Summary" sheet) do not need to be in quotes when building a string in VBA
    • (not an error, per say) You don't need to do .Select as you can set the formula of the cell directly.

    Update your code with the following

    Sub Reset()
    
    Dim X As Integer
    
    For X = 0 To 19
        ' Broken up on several lines for clarity
        Sheets("Summary").Cells(11 + X, 13).Formula = 
            "=INDEX(YMAX!$A:$W,MATCH(Summary!$J$4" & " " & _
                "Summary!$J$5" & "    " & _
                "11,YMAX!$B:$B,0),MATCH(" & _
                    Sheets("Summary").Cells(11 + X,9).Address & _
                  ",YMAX!$1:$1,0))"
    
    Next X
    
    End Sub
    

    I'm not sure if that's the formula you want exactly, but it's what i interpreted given your current code. Let me know if that works for you.