2016-11-28 76 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