简体   繁体   中英

How to use VLookup in Word VBA?

I am trying to prompt user to for an input, then lookup that information from an Excel Report. And populate the Word Document, but I am not sure where the mistake is. I tried to base the code from this question and this question .

It is giving me Run-time error '438' Object doesn't support this property or method. I know it is the way I use the method, could you please point me to the right direction? Thank you!

Sub PopulateForm()
    Dim objExcel As New Excel.Application
    Dim exWb As Excel.Workbook
    Dim cin_number As String
    Dim result As String

    ' Prompt user for input
    cin_number = InputBox("Please enter the CIN#", "Input")

    ' Open the cover sheet letter
    Set exWb = objExcel.Workbooks.Open("U:\HRA Cover Sheet Data.xls")

    ' Perform the VLookup...
    result = objExcel.WorksheetFunction.VLookup(cin_number, _
        exWb.Range("A:F"), 5, False)

    ' Testing the output
    MsgBox result

    exWb.Close

    Set exWb = Nothing
End Sub

I am using Word 2003, and Window XP.

You are trying to take a range of exWb which is a workbook, not a worksheet. Try

result = objExcel.WorksheetFunction.VLookup(cin_number, _
    exWb.ActiveSheet.Range("A:F"), 5, False)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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