简体   繁体   中英

Index Match Excel VBA, Error

I'm working on a project for my marketing class. I keep getting the following error, and I can't figure out how to resolve it. "Object variable or With block variable not set." Can someone please take a look at this?! It would be super appreciated!

    Dim k as Integer
    Dim EndRow As Integer
    Dim lookupRange1 As Range
    Dim lookupRange2 As Range
    Dim lookupValue1 As Integer

    EndRow = Range("M" & Rows.Count).End(xlUp).Row
    lookupRange1 = Sheets("Data_Main").Range("C2:C50000")
    lookupRange2 = Sheets("Data_Main").Range("A2:A50000")

    With Application.WorksheetFunction
        For k = 2 To EndRow
           lookupValue1 = Cells(k, 13).Value
    Cells(k, 15).Formula = ".Index(lookupRange1, .Match(lookupValue1, lookupRange2, 0))"
        Next k
    End With

Try to use following code:

    Dim k As Long
    Dim EndRow As Long
    Dim lookupRange1 As Range
    Dim lookupRange2 As Range
    Dim lookupValue1 As Integer

    EndRow = Range("M" & Rows.Count).End(xlUp).Row
    Set lookupRange1 = Sheets("Data_Main").Range("C2:C50000")
    Set lookupRange2 = Sheets("Data_Main").Range("A2:A50000")

    For k = 2 To EndRow
       lookupValue1 = Cells(k, 13).Value
       Cells(k, 15).Formula = "=Index(" & lookupRange1.Address & ", Match(" & lookupValue1 & ", " & lookupRange2.Address & ", 0))"
    Next k

1) since lookupRange1 and lookupRange2 are objects, you need to use Set

2) your Cells(k, 15).Formula = "..." statement was wrong. See correct one in my code

3) for EndRow it's better to use Long type, because max value of Integer is only 32767

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