使用Vlookup将数据从已关闭的工作簿提取到用户表单

时间:2017-06-07 09:46:56

标签: vba

在以下代码中,我将封闭电子表格中的值复制到用户表单,但它失败并显示error 1004

  

"无法获得Vlookup propoerty"。

我的代码如下:

If TextBox1.Value = "" Then
   MsgBox "Enter Employee Number", vbExclamation, "Error Message"

   Exit Sub

End If

Set wb = Workbooks.Open("Z:\PROD  - Production related info\QUALITY\KAIZEN TEAM\Weekly Rejects\Dropdown_List_Database\Dropdown_Lists.xlsx")

Dim myRange As Range
Set myRange = Worksheets("Users").Range("A2:F1000")

UserForm1.TextBox2.Value = 
Application.WorksheetFunction.VLookup(UserForm1.TextBox1.Value, myRange, 2, False)

1 个答案:

答案 0 :(得分:0)

如果找不到您要查找的值,则

VLookup会在通过Application.WorksheetFunction对象调用时引发错误。您可以通过向函数添加错误捕获来处理此问题:

测试数据

Row/Col     A   B
1           x   XXX
2           y   YYY
3           z   ZZZ

示例A

Public Sub XX()
On Error Resume Next    ' Ignore errors.  WARNING: Will ignore **all** errors.
Dim result As Variant   ' Holds result of vlookup.

    ' Can find value, no error.
    result = Application.WorksheetFunction.VLookup("x", Range("Sheet1!A1:B3"), 2, False)
    MsgBox result

    ' Cannot find value, raises an error.
    result = Application.WorksheetFunction.VLookup("a", Range("Sheet1!A1:B3"), 2, False)

    ' Check for error.
    ' 1004 = cannot find value.
    ' Make sure you handle all other errors.
    If Err.Number = 1004 Then

        MsgBox "Cannot find value"
        Err.Clear
    Else

        MsgBox Err.Description
        Err.Clear
    End If
End Sub

另一种方法允许您直接调用VLookup。此方法不需要错误捕获:

示例B

Dim Result As Variant

' Value XXX wrote to Result.
Result = [Vlookup("x", Sheet1!A1:B3, 2, False)]

' Value Error 2042 wrote to Result.
Result = [Vlookup("a", Sheet1!A1:B3, 2, False)]

我更喜欢第二种方法。忽略错误会导致以后很难调试代码。

有关通过VBA使用VLookup的更多信息,我建议您阅读此blog post