我如何做我的索引/匹配在VBA中工作?

我试图创build一个使用索引/匹配函数的macros来匹配数据,并将数据从一个表单拉到另一个表单中。 我在Excel中做了它,它的工作完美。 然而,报告是“dynamic的”(大小的变化),所以我需要我的代码的最后一行是dynamic的。 以下是我所做的。 我现在正在得到一个“types不匹配”的错误(我强调“现在”,因为每次我find一个错误的解决scheme另一个popup)。

Dim prosheet As Worksheet Dim prosheet2 As Worksheet Set prosheet2 = ThisWorkbook.Sheets("shipstation") Set prosheet = ThisWorkbook.Sheets("macrotestfb") lr1 = prosheet.Cells(Rows.Count, 1).End(xlUp).Row lr2 = prosheet2.Cells(Rows.Count, 1).End(xlUp).Row lrship = prosheet.Cells(Rows.Count, 10).End(xlUp).Row lrindex = prosheet2.Cells(Rows.Column, 14).End(xlUp).Row 'CALCULATE SHIPPING COST For x = prosheet.range("j6") To lrship x = Application.WorksheetFunction.Index(prosheet2.range("a1:n" & lrindex), Application.WorksheetFunction.Match(prosheet.range("a6:a" & lr1), prosheet2.range("a1:a" & lr2), 0), prosheet2.range("f2")) Next x 

匹配,在其非数组forms,只喜欢第一个标准中的一个值,而不是一个范围。

另外WorksheetFunction.Match会抛出一个错误,如果没有find匹配,将停止代码。

我喜欢把比赛拉进自己的路线,并testing错误。

我也调整了你的For语句。

search整个列没有任何不利之处,所以我摆脱了你最后一行的search,因为他们不需要。

 Dim prosheet As Worksheet Dim prosheet2 As Worksheet Dim x As Long Dim t As Long Set prosheet2 = ThisWorkbook.Sheets("shipstation") Set prosheet = ThisWorkbook.Sheets("macrotestfb") lrship = prosheet.Cells(Rows.Count, 1).End(xlUp).Row 'CALCULATE SHIPPING COST For x = 6 To lrship t = 0 On Error Resume Next t = Application.WorksheetFunction.Match(prosheet.Range("A" & x), prosheet2.Range("A:A"), 0) On Error GoTo 0 If t > 0 Then prosheet.Cells(x, "J").Value = prosheet2.Range("F"&t) Else prosheet.Cells(x, "J").Value = "Item does not Exist" End If Next x 

注意:

您可以在VBA中使用Application.Match ,而不是您可能在工作表上使用的Index / Match组合。 像这样的东西:

 Sub GetMatch Dim indexRng As Range, matchRng as Range Set indexRng = ThisWorkbook.Worksheets("Sheet1").Range("A1:A10") Set matchRng = ThisWorkbook.Worksheets("Sheet1").Range("B1:B10") debug.print indexRng.Cells(Application.Match("something",matchRng,0)).Value End Sub