我试图创建一个使用索引/匹配函数来匹配数据并将数据从一个工作表拉到另一个工作表的宏。我在Excel中做到了它完美无缺。然而,报告是动态的" (大小改变)所以我需要我的代码的最后一行也是动态的。 以下是我所做的。我现在得到了#34;类型不匹配"错误(我强调"现在"因为每次我找到一个错误的解决方案时,另一个流行音乐都会出现)。
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
答案 0 :(得分:2)
匹配,以非数组形式,只喜欢第一个标准中的一个值,而不是范围。
如果找不到匹配项,WorksheetFunction.Match也会抛出一个会停止代码的错误。
我喜欢将比赛拉到自己的路线并测试错误。
我也调整了你的For语句。
搜索整个列没有任何不利因素,因此我删除了一些最后一行搜索,因为它们不需要。
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
答案 1 :(得分:0)
注意:
您可以在VBA中使用Index
,而不是可以在工作表中使用的Match
/ Application.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