首页 > 解决方案 > 将数据从 Outlook 导入 Excel

问题描述

我目前正在为 Excel 开发一个宏/加载项,以从 Outlook 导入电子邮件。

当我使用符合我设置的所有条件的电子邮件进行测试时,它工作得很好。

但是,当我使用多个电子邮件进行测试时,我收到了“下标超出范围”错误。

我从左到右和从右到左阅读了我的代码,但我无法找出我做错了什么。

这是我到目前为止的代码(我很抱歉代码混乱,一切顺利后我会清理它)。

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

带有错误的突出显示的行是“Range("batch_reference").Offset(i, 0).Value = Left(ar(i), WorksheetFunction.Find("-", ar(i), 1) - 1)"

关于我所缺少的任何见解?

提前致谢!

标签: excelvba

解决方案


当你创建你的ar数组时,它将是一个0..n 每次的数组。因此,虽然i将指向第一个邮件项的所需数组元素,但当您处理第二个邮件项时,ar仍然是一个0基于数组,但i指向工作表上的下一行,这将远大于0.

建议类似:

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

也许:

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

推荐阅读