简体   繁体   English

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

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

I can't get an external workbook to use Vlookup to return the value of a different column. 我无法使用外部工作簿来使用Vlookup返回不同列的值。

I am trying to take a word document, enter an ID number into a text box, have vlookup find the ID number in an external document then return a name from the next column. 我正在尝试获取Word文档,在文本框中输入ID号,让vlookup在外部文档中找到ID号,然后从下一列返回名称。 Then the name will populate a different textbox and the date the number was entered will go in a third box. 然后,该名称将填充另一个文本框,而输入数字的日期将出现在第三个框中。 Right now EMPID.txt has only two columns A: EmpNum and B: EmpName. 现在,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 get assigned and shows as the value in a message box but nothing gets returned or assigned to result. emp_number被分配并显示为消息框中的值,但没有返回任何结果或将其分配给结果。 The date is updated in the third textbox anytime the first "lost focus". 每当第一个“失去焦点”时,日期就会在第三个文本框中更新。

WorksheetFunction works with Application Object, Since You already declared XlApp as Workbook change the line to WorksheetFunction与Application Object一起使用,因为您已经将XlApp声明为Workbook,所以将行更改为

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

and it is working. 它正在工作。 Also if emp_number is entered as Number in the workbook, then make the following changes 另外,如果在工作簿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