循环VBA中的"索引匹配"函数出错



我的索引匹配循环在一个受限制的样本中运行得很好,但当我将其扩展到整个样本时,它崩溃了。问题是,在某个时刻,它会找到在行范围内找不到的值。它完全停止在那个单元格中写入。我尝试使用isError,但它没有改变任何内容,代码也停在同一个单元格中。

你能帮帮我吗?!

谢谢!

Set inputs = Sheets("Inputs")
Set raw = Sheets("Raw")
Set interm = Sheets("Rel_Raw")
Set finaldata = Sheets("Data")

For i = cols + 1 To cols_2 Step 1
For j = 2 To entries_r Step 1
If Not IsError(finaldata.Cells(j, i).Value = Application.Index(interm.Range(interm.Cells(1, 1), interm.Cells(dim_r, dim_c)), IsError(Application.Match(finaldata.Cells(j, 1).Value, interm.Columns(1), 0)), IsError(Application.Match(finaldata.Cells(1, i).Value, interm.Rows(1), 0)))) Then
finaldata.Cells(j, i).Value = Application.Index(interm.Range(interm.Cells(1, 1), interm.Cells(dim_r, dim_c)), Application.Match(finaldata.Cells(j, 1).Value, interm.Columns(1), 0), Application.Match(finaldata.Cells(1, i).Value, interm.Rows(1), 0))
Else
finaldata.Cells(j, i).Value = 0
End If
Next j
Next i

您的代码可以从将Application.Match部分拆分为自己的行中受益。将Application.Match的结果存储在Variant中,那么只使用IsNumeric来测试它们是否是一个数字可能会更容易,如果是,则继续在Application.Index中使用它们。

Dim rowMatch as Variant
rowMatch = Application.Match(finaldata.Cells(j, 1).Value, interm.Columns(1), 0)
Dim colMatch as Variant
colMatch = Application.Match(finaldata.Cells(1, i).Value, interm.Rows(1), 0)
Dim lookupRang as Range
Set lookupRange = interm.Range(interm.Cells(1, 1), interm.Cells(dim_r, dim_c))
If IsNumeric(rowMatch) And IsNumeric(colMatch) Then
finaldata.Cells(j, i).Value = Application.Index(lookupRange, rowMatch, colMatch)
Else
finaldata.Cells(j, i).Value  = 0
End If

最新更新