繁体   English   中英

使用VBA在Word的外部工作簿上执行Vlookup

[英]Using VBA to perform Vlookup on an external workbook from Word

我无法使用外部工作簿来使用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被分配并显示为消息框中的值,但没有返回任何结果或将其分配给结果。 每当第一个“失去焦点”时,日期就会在第三个文本框中更新。

WorksheetFunction与Application Object一起使用,因为您已经将XlApp声明为Workbook,所以将行更改为

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

它正在工作。 另外,如果在工作簿emp_number输入为Number,则进行以下更改

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM