如何在 Word VBA 中使用 VLookup?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24294226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 03:30:37  来源:igfitidea点击:

How to use VLookup in Word VBA?

vbams-wordword-vbaword-2003

提问by George

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 questionand this question.

我试图提示用户输入,然后从 Excel 报告中查找该信息。并填充 Word 文档,但我不确定错误在哪里。我试图根据这个问题这个问题来编写代码。

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!

它给了我运行时错误“438”对象不支持此属性或方法。我知道这是我使用该方法的方式,请您指出正确的方向吗?谢谢!

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.

我使用的是 Word 2003 和 Window XP。

回答by Joe

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

您正在尝试采用exWb工作簿而不是工作表的范围。尝试

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