获取电子邮件地址从outlook到excel

8ulbf1ek  于 2023-02-10  发布在  其他
关注(0)|答案(3)|浏览(189)

发现下面的代码和我试图得到我的Outlook收件箱中的电子邮件地址到Excel,但在行设置objfolder错误

Sub getemail()
Dim objFolder As MAPIFolder
Dim strEmail As String
Dim objItem As Object
Dim counter As Integer
counter = 2

Set objFolder = Application.GetNamespace("Mapi").GetDefaultFolder(olFolderInbox)
For Each objItem In objFolder.Items
    If objItem.Class = olMail And objItem.ReceivedTime >= DateAdd("yyyy", -1, Now) Then
        strEmail = objItem.SenderEmailAddress
        Cells(counter, 1).Value = strEmail
        counter = counter + 1
    End If
Next
End Sub
ql3eal8s

ql3eal8s1#

首先,不要遍历文件夹中的所有项目-文件夹可以包含数千条消息,使用Items.Find/FindNextItems.Restrict
其次,收件箱文件夹可以包含MailItem以外的项目,如ReportItemMeetingItem,它们不暴露SenderEmailAddress属性。检查Class属性(由所有OOM对象暴露),您确实有一个MailItem对象。
最后,Application内部变量指向Excel VBA中的Excel.Application对象。除非在Outlook VBA中运行代码,否则需要显式创建Outlook.Application对象的示例。

set OlApp = CreateObject("Outlook.Application")
Set objFolder = OlApp.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
set restrictedItems = objFolder.Items.Restrict("[ReceivedTime] >= '02-07-2023' ")
For Each objItem In restrictedItems
    If objItem.Class = olMail Then
        strEmail = objItem.SenderEmailAddress
        Cells(counter, 1).Value = strEmail
        counter = counter + 1
    End If
Next
hmae6n7t

hmae6n7t2#

我不确定这是否与晚绑定/早绑定问题有关。但您可以尝试将“olderinbox”更改为6。
如果要使用早期绑定,请确保在引用中启用了Microsoft Outlook XX.X对象库。
我通常会使用后期绑定,它会简单得多,您不必处理引用库版本问题。当与其他使用不同Excel版本的同事或朋友共享子例程时

Sub Get_Name()

    Dim OLApp As Object
    Dim oNameSpace As Object
    Dim oFolder As Object
    Dim oMail As Object

    Set OLApp = CreateObject("Outlook.Application")
    Set oNameSpace = OLApp.GetNameSpace("MAPI")
    Set oFolder = oNameSpace.GetDefaultFolder(6) 'olFolderInbox: 6, Inbox folder

    For Each oMail In oFolder.items
        On Error Resume Next
        Debug.Print oMail.SenderEmailAddress
        'Do your stuff here....
        On Error GoTo 0
    Next oMail

End Sub
sg2wtvxw

sg2wtvxw3#

by @Dmitry确保将Outlook添加为项目首选项

Sub getemail()
Dim OLApp As Object
Dim objFolder As Object
Dim objItem As Object
Dim restrictedItems As Object
Dim olFolderInbox As Object
Dim strEmail As String
Dim counter As Integer
counter = 2

Set OLApp = CreateObject("Outlook.Application")
Set objFolder = OLApp.GetNamespace("MAPI").GetDefaultFolder(6)
Set restrictedItems = objFolder.Items.Restrict("[ReceivedTime] >= '02-07-2023' ")
For Each objItem In restrictedItems
If objItem.Class = 43 Then
strEmail = objItem.SenderEmailAddress
Cells(counter, 1).Value = strEmail
counter = counter + 1
End If
MsgBox "Email address copied"
Next
End Sub

相关问题