Search code examples
vbams-wordword-2003

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.


Solution

  • 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)