简体   繁体   中英

Importing data from Outlook to Excel

I am currently developing a macro/add-in for Excel, to import e-mails from Outlook.

When I tested with an e-mail that fit all the conditions set by me, it worked just fine.

However, when I tested with more than one e-mail, I got a 'Subscript out of range' error.

I've read my code left to right and right to left but I can't find out what I did wrong.

Here's the code I have so far (I'm sorry for the messy code, I'll clean it up after everything is running smoothly).

Sub GetDataFromOutlook()

Dim OutlookApp As Outlook.Application
Dim OutlookNamespace As Namespace
Dim Folder As MAPIFolder
Dim OutlookMail As Variant
Dim i As Integer
'Dim LR As Long
Dim dbf As Worksheet
Dim ar() As String
ReDim ar(0 To i)

Set OutlookApp = New Outlook.Application
Set OutlookNamespace = OutlookApp.GetNamespace("MAPI")
Set Folder = OutlookNamespace.GetDefaultFolder(olFolderInbox)
Set dbf = Sheets("DBF")
'LR = dbf.Range("A" & Rows.Count).End(xlUp).Row + 1
i = 0

For Each OutlookMail In Folder.Items
ar() = Split(OutlookMail.Body, ",")
    If InStr(OutlookMail.Subject, "Exportation of purchase order") > 0 Then
        For Each Item In ar
            Range("batch_reference").Offset(i, 0).Value = Left(ar(i), WorksheetFunction.Find("-", ar(i), 1) - 1)
            Range("batch_reference").Offset(i, 0).Columns.AutoFit
            i = i + 1
        Next Item
    End If
Next OutlookMail

    Columns("A:A").Select
    dbf.Range("$A$1:$A$100").RemoveDuplicates Columns:=1, Header:=xlYes
    dbf.Sort.SortFields.Clear
    dbf.Sort.SortFields.Add Key:=Range("A1"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal

    With ActiveWorkbook.Worksheets("DBF").Sort
        .SetRange Range("A2:A100")
        .Header = xlNo
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With


Set Folder = Nothing
Set OutlookNamespace = Nothing
Set OutlookApp = Nothing

End Sub

The highlighted line with the error is "Range("batch_reference").Offset(i, 0).Value = Left(ar(i), WorksheetFunction.Find("-", ar(i), 1) - 1)"

Any insight on what I'm missing?

Thanks in advance!

When you create your ar array, it will be an array of 0..n each time . So, although i will point to the desired array element of the first mail item, when you process the second mail item, ar again is a 0 based array, but i is pointing to the next row on the worksheet, which will be much greater than 0 .

Suggest something like:

 Range("batch_reference").Offset(i, 0).Value = Left(Item, WorksheetFunction.Find("-", Item, 1) - 1)

Or, perhaps:

Range("batch_reference").Offset(i, 0).Value = Split(Item, "-")(0)

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