简体   繁体   中英

VBA Outlook/Excel

I am writing a vba sub in outlook that will: grab a unique value from the mail, look for that value in the column of an excel file, and return an associated value. I am working with an the .find function from the excel library to lookup my unique value in the excel, however, find is supposed to return a range of the first occurrence of my value but I cannot assign that value to the variable: pointer. I cannot reference it. Any insights appreciated. thank you!

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

Where you are trying to set an object reference you need the Set keyword. Try this:

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

You should also handle the scenario where the reference is not found. This can be done like so:

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

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