vba - 无法使 vlookup 工作

标签 vba excel

我运行这组代码,它返回一个错误:

运行时错误“1004”无法获取 WorksheetFunction 类的 Vlookup 属性。

我已经在另一个子例程中进行了一个vlookup。 这段代码有什么问题吗?我进行调试,错误出现在策略框中。

Sub LinkPolicyNum()
Dim r As Integer
Dim policynum As Variant
Dim lookup_num As Range
Dim policybox As Variant


    r = ActiveCell.Row
    'Row number of the Selected Cell

    policynum = ActiveSheet.Cells(r, 3).Value

    Set lookup_num = ThisWorkbook.Sheets("PolicyDetails").Range("a1:z5000")

    policybox = Application.WorksheetFunction.VLookup(policynum, lookup_num, 3, False)
    'to match the policy number to the policy details

    MsgBox policynum
    MsgBox policybox



End Sub

最佳答案

您的代码似乎没有任何问题。您将看到使用 WorksheetFunction 版本的函数时发生的结果,并且没有返回结果。具体来说,它们会抛出错误并中断 VBA 的执行。在这种情况下,如果您在工作簿中而不是在 VBA 中尝试相同的公式,您将收到某种形式的错误(可能是 #N/A#VALUE!) .

如果您想防止这种情况发生,最简单的方法就是更改为使用 Application.VLookup 而不是 Application.WorksheetFunction.VLookup。尽管没有智能感知来帮助执行此功能,但除了错误处理之外,它的行为与其他功能相同。如果函数的非 WorksheetFunction 版本出现错误,它将返回错误而不是抛出错误。这允许您检查错误,然后继续执行您的代码。

如果您认为应该在此处使用 VLOOKUP 查找值,那么您可以开始检查文本/数字和其他类似内容之间是否不匹配。我会检查公式而不是 VBA。

这是使用其他函数形式并捕获错误的示例。

Sub LinkPolicyNum()
    Dim r As Integer
    Dim policynum As Variant
    Dim lookup_num As Range
    Dim policybox As Variant

    r = ActiveCell.Row
    'Row number of the Selected Cell

    policynum = ActiveSheet.Cells(r, 3).Value

    Set lookup_num = ThisWorkbook.Sheets("PolicyDetails").Range("a1:z5000")

    policybox = Application.VLookup(policynum, lookup_num, 3, False)
    'to match the policy number to the policy details

    If IsError(policybox) Then
        'possibly do something with the "not found" case
    Else
        MsgBox policynum
        MsgBox policybox
    End If

End Sub

此问题引用:http://dailydoseofexcel.com/archives/2004/09/24/the-worksheetfunction-method/

关于vba - 无法使 vlookup 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29939770/

相关文章:

excel - 通过 ODBC 将 Excel 连接到 PostgreSQL

javascript - 使用 VBA 单击网页按钮

arrays - 使用 Replace 方法在 Excel VBA 中输入长数组公式作为解决方法

mysql - Excel 数组公式与 MySQL 等价

c# - 从 Excel VSTO 和 Win Form 运行 WPF 应用程序

xml - 如何在 Excel vba 中创建 CDATA 标签?

VBA - 在子程序中调用 Dir() 时使用 Dir() 循环

excel - Replace() 来自 Shell 的图像尺寸字符串中的问号

vba - Excel VBA - PivotItems 返回无效值

string - 将带有克拉的字符串转换为数字(并求值)