Excel VBA无效的过程调用或参数时,查找找不到结果

我在这里写了一些代码,得到了极其有用的用户Jeeped的帮助。 唯一的问题是,当vlookup 没有find结果时,我得到了错误Invalid Procedure Call or Argument 。 如果发现结果,似乎没有问题。

我希望它只是返回#N /就好像它找不到结果。 你能帮我解决这个问题吗? 另外我还有500列,所以如果有更简单的方法来解决这个问题,那就太棒了。 我还在学习VBA。 非常感谢。

  Dim v As Long, vWSs As Variant, Mrange As Range, Vrange As Range Dim wsMaster As Worksheet: Set wsMaster = Workbooks("LBImportMacroTemplate.xlsm").Worksheets("MasterTab") Dim mf_iA_TEXT As String: mf_iA_TEXT = "iA" Dim mf_pLN_TEXT As String: mf_pLN_TEXT = "pLN" 'ET CETERA vWSs = Array("B", "E", "L", "I", "T") With Workbooks("LBImportMacroTemplate.xlsm") Set Mrange = Nothing: Set Vrange = Nothing ' With ActiveSheet lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row MsgBox lastrow End With ' For v = LBound(vWSs) To UBound(vWSs) If CBool(Application.CountIf(.Sheets(vWSs(v)).Range("A2:ZA2"), mf_iA_TEXT)) Then Set Mrange = .Sheets(vWSs(v)).Range("A2:ZA2") Set Vrange = .Sheets(vWSs(v)).Range("A:ZA") mf_iA = Application.Match(mf_iA_TEXT, Mrange, 0) Exit For End If Next v For i = 2 To lastrow wsMaster.Cells(i, 2) = Application.VLookup(wsMaster.Cells(i, 1), Vrange, mf_iA, 0) Next i Set Mrange = Nothing Set Vrange = Nothing ' For v = LBound(vWSs) To UBound(vWSs) If CBool(Application.CountIf(.Sheets(vWSs(v)).Range("A2:ZA2"), mf_pLN_TEXT)) Then Set Mrange = .Sheets(vWSs(v)).Range("A2:ZA2") Set Vrange = .Sheets(vWSs(v)).Range("A:ZA") mf_pLN = Application.Match(mf_pLN_TEXT, Mrange, 0) Exit For End If Next v For i = 2 To lastrow wsMaster.Cells(i, 3) = Application.VLookup(wsMaster.Cells(i, 1), Vrange, mf_pLN, 0) Next i Set Mrange = Nothing Set Vrange = Nothing 

如果VRange对象是VRange你的VRange语句将会失败并显示描述的错误信息。

很难理解你想要做什么,但是我会试着去分解它。 在这里你有一个循环,返回TrueCBoolexpression式的第一个实例。

 For v = LBound(vWSs) To UBound(vWSs) If CBool(Application.CountIf(.Sheets(vWSs(v)).Range("A2:ZA2"), mf_iA_TEXT)) Then Set Mrange = .Sheets(vWSs(v)).Range("A2:ZA2") Set Vrange = .Sheets(vWSs(v)).Range("A:ZA") mf_iA = Application.Match(mf_iA_TEXT, Mrange, 0) Exit For End If Next v 

在这一点上, 假设Exit For语句退出循环VRange对象应该存在并且是一个有效的范围,所以下一个循环不应该失败:

  For i = 2 To lastrow wsMaster.Cells(i, 2) = Application.VLookup(wsMaster.Cells(i, 1), Vrange, mf_iA, 0) Next i 

但是,如果第一个循环没有“find” mf_iA_Text值,那么VRange对象不是一个有效的范围,那会导致错误。

build议通过将第二个循环放入第一个循环来修改:

 For v = LBound(vWSs) To UBound(vWSs) If CBool(Application.CountIf(.Sheets(vWSs(v)).Range("A2:ZA2"), mf_iA_TEXT)) Then Set Mrange = .Sheets(vWSs(v)).Range("A2:ZA2") Set Vrange = .Sheets(vWSs(v)).Range("A:ZA") mf_iA = Application.Match(mf_iA_TEXT, Mrange, 0) For i = 2 To lastrow wsMaster.Cells(i, 2) = Application.VLookup(wsMaster.Cells(i, 1), Vrange, mf_iA, 0) Next i Exit For End If Next v