2016-11-28 75 views
0

我在Outlook中编写了一个vba子文件,它将:从邮件中获取唯一值,在excel文件的列中查找该值,并返回相关值。我正在使用excel库中的.find函数来查找我在Excel中的唯一值,但是,find应该返回第一次出现的值的范围,但我无法将该值赋给变量:pointer。我不能参考它。任何见解都会被赞赏谢谢!VBA Outlook/Excel

Sub OTM1S() '(ByVal Item As Object) 
    Dim xlApp As Object 
    Dim wb As Workbook 
    Dim pointer As Range 
    Set xlApp = CreateObject("Excel.Application") 
    Set wb = xlApp.Workbooks.Open("I:\referencefile.xlsx") 

    'On Error Resume Next 
    pointer = wb.Sheets("Bonds").Range("A1:A10000").Find("XS1058142081") 
    MsgBox pointer.Offset(0, 1) 
    'On Error GoTo 0 

    wb.Save 
    wb.Close 

End Sub 

回答

2

在试图设置对象引用时,您需要Set关键字。试试这个:

Sub OTM1S() '(ByVal Item As Object) 
    Dim xlApp As Object 
    Dim wb As Workbook 
    Dim pointer As Range 
    Set xlApp = CreateObject("Excel.Application") 
    Set wb = xlApp.Workbooks.Open("I:\referencefile.xlsx") 

    'On Error Resume Next 
    Set pointer = wb.Sheets("Bonds").Range("A1:A10000").Find("XS1058142081") 
    MsgBox pointer.Offset(0, 1) 
    'On Error GoTo 0 

    wb.Save 
    wb.Close 

End Sub 

您还应该处理未找到引用的情况。这可以这样完成:

Set pointer = wb.Sheets("Bonds").Range("A1:A10000").Find("XS1058142081") 
If Not pointer Is Nothing Then 
    MsgBox pointer.Offset(0,1) 
Else 
    MsgBox "Sorry, couldn't find that in the specified range." 
End If