【问题标题】:Using VBA to perform Vlookup on an external workbook from Word使用 VBA 从 Word 对外部工作簿执行 Vlookup
【发布时间】:2019-02-16 03:16:55
【问题描述】:

我无法让外部工作簿使用 Vlookup 返回不同列的值。

我正在尝试获取一个 word 文档,在文本框中输入一个 ID 号,让 vlookup 在外部文档中找到 ID 号,然后从下一列返回一个名称。然后名称将填充一个不同的文本框,输入数字的日期将出现在第三个框中。现在 EMPID.txt 只有两列 A:EmpNum 和 B:EmpName。

Private Sub VerID_LostFocus()

    Dim emp_number As String
    Dim xlApp As Excel.Workbook

    Set xlApp = Excel.Workbooks.Open("filepath\EmpID.xlsx")

    emp_number = VerID.Text

    MsgBox emp_number

    On Error Resume Next

    result = Excel.WorksheetFunction.VLookup(emp_number, xlApp.Worksheets("Sheet1").Range("A:B"), 2, False)
    On Error GoTo 0

    If result <> "" Then MsgBox result

    MsgBox result

    VerSig.Text = result

    Set xlApp = Nothing

    VerDate.Value = Format(Date, "mm/dd/yyyy")

End Sub

emp_number 被分配并显示为消息框中的值,但没有返回或分配给结果。只要第一个“失去焦点”,日期就会在第三个文本框中更新。

【问题讨论】:

  • 注释掉/删除On Error Resume Next。它会抛出错误吗?

标签: excel vba ms-word


【解决方案1】:

WorksheetFunction 与应用程序对象一起使用,因为您已经将 XlApp 声明为工作簿,请将行更改为

Result = xlApp.Application.WorksheetFunction.VLookup(emp_number, Worksheets("Sheet1").Range("A:B"), 2, False)  

它正在工作。此外,如果 emp_number 在工作簿中输入为数字,则进行以下更改

Dim emp_number As Variant 
'
'
'
'
emp_number = Val(VerID.Text)

【讨论】:

  • 做到了!非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多