2014-01-23 109 views
0

我正在爲我的營銷課程開展一個項目。我不斷收到以下錯誤,我無法弄清楚如何解決它。 「對象變量或未設置塊變量」。有人可以看看這個嗎?!這將是超級讚賞!索引匹配Excel VBA,錯誤

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 

回答

1

嘗試使用下面的代碼:

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)由於lookupRange1lookupRange2都是對象,你需要使用Set

2)您Cells(k, 15).Formula = "..."說法是錯誤的。爲EndRow參見正確的在我的代碼

3),最好使用Long類型,因爲Integer最大值僅爲32767