Vba Excel Vlookup搜索值为字符串

时间:2017-11-08 12:49:31

标签: vba excel-vba excel

以下代码不起作用

  

运行时错误1004

VlookSrc(VBA中的Dim As String)是我们在Range("KV5:KW105673")中查找的值。它是不同单元格的组合,具体取决于c和d,以及它们之间的字符串/DIR/。 在本地窗口中,可以看到Excel识别正确的字符串。 我们使用IfError函数,因为找不到值。 运行错误1004随工作表功能一起提供。

    If Cells(3, d) = Cells(c, 33) Then
        VlookSrc = Cells(c, 48).Value & "/DIR/" & Cells(4, d).Value
       Cells(c, d) = Application.WorksheetFunction.IfError(Application.WorksheetFunction.VLookup(VlookSrc, Range(Cells(5, 308), Cells(105673, 309)), 2, False), 0)
    Else
        Cells(c, d) = 0
    End If

2 个答案:

答案 0 :(得分:0)

删除WorksheetFunction,因为这总是会引发运行时错误(在线有很多关于此问题),而Application允许测试错误。

Sub x()

If Cells(3, d) = Cells(c, 33) Then
    VlookSrc = Cells(c, 48).Value & "/DIR/" & Cells(4, d).Value
    Cells(c, d) = Application.IfError(Application.VLookup(VlookSrc, Range(Cells(5, 308), Cells(105673, 309)), 2, False), 0)
Else
    Cells(c, d) = 0
End If

End Sub

答案 1 :(得分:0)

您不能在 VBA 中使用IfError(),而是:

Sub luxation()
    Dim v
    With Application.WorksheetFunction
        v = 0
        On Error Resume Next
            Cells(c, d) = .VLookup(VlookSrc, Range(Cells(5, 308), Cells(105673, 309)), 2, False)
        On Error GoTo 0
    End With
End Sub
相关问题