如何从 Outlook 调用 VBA 代码然后从 Excel 调用 VBA 代码?

How to call VBA code from Outlook then VBA code from Excel?

我有一个项目需要 Outlook 和 Excel 连接。我需要的是:

  1. 从 Outlook 收件箱中提取未读电子邮件的数据(接收日期、发件人、主题),然后粘贴到 Excel。请参阅下面的代码。

  2. 数据粘贴到Excel后,格式化提取的数据(我已经在Excel中有代码)然后保存Excel文件。

  3. 将提取的电子邮件标记为"Read"

我的问题是:

Outlook 中用于提取数据的代码:

Sub Extract()
Set myOlApp = Outlook.Application
Set mynamespace = myOlApp.GetNamespace("mapi")
Set myfolder = myOlApp.ActiveExplorer.CurrentFolder
Set xlobj = CreateObject("Excel.Application")
xlobj.Visible = True
xlobj.workbooks.Add
'Set Heading
xlobj.Range("a" & 1).Value = "Received time"
xlobj.Range("b" & 1).Value = "Subject"
xlobj.Range("c" & 1).Value = "Importance"
xlobj.Range("d" & 1).Value = "Sender"
For i = 1 To myfolder.Items.Count
    Set myitem = myfolder.Items(i)
    xlobj.Range("a" & i + 1).Value = myitem.ReceivedTime
    xlobj.Range("b" & i + 1).Value = myitem.Subject
    xlobj.Range("c" & i + 1).Value = myitem.Importance
    xlobj.Range("d" & i + 1).Value = myitem.SenderName
Next
End Sub

有没有办法让我自动 运行 宏(例如:运行 早上 7 点、下午 2 点和早上 6 点的宏)?

未内置于 Excel。您可以在 Windows(附件 --> 系统工具 --> 任务计划程序)中尝试计划任务来打开 Excel 文件(包括文件路径和名称的参数)。您需要在打开时制作 Excel 运行 该宏(右键单击 sheet,然后 "View Code" 添加):

Private Sub Workbook_Open()
    Call MacroThatYouWantToRun()
End Sub

更多详情 --> http://support.microsoft.com/kb/265113

我不确定这是否可以在 Outlook 中轻松完成。也许这有帮助:Outlook VBA - Run a code every half an hour

提取信息后如何将电子邮件设置为"read"?

Outlook 项目显然有一个“.UnRead”属性。只需将要标记为已读的项目设置为 False。

我如何 select 只提取 "Unread" 封电子邮件?

我不是专家,但最坏的情况是,您可以 运行 遍历所有文件夹项目并检查每个项目是否 属性。如果 .UnRead 属性 设置为 True,执行您的命令,即将其一​​些属性复制到 Excel.

此外:运行 浏览 Outlook 文件夹中所有项目的方法之前已在此处讨论过:

  • Can I iterate through all Outlook emails in a folder including sub-folders?
  • Iterate all email items in a specific Outlook folder
  • outlook vba select messages in sub-folder

如何将我的 outlook 宏连接到我的 excel 宏并自动 运行 它?

我认为没有必要。您可以从一个应用程序访问另一个应用程序——就像您在示例中所做的那样 (Outlook --> Excel)。如果您想反过来(Excel --> Outlook),请考虑以下内容:

' This is running in Excel, not Outlook
Dim objOutlook As Object
Set objOutlook = CreateObject("Outlook.Application")
With objOutlook
    ' Specify the commands you want to run in Outlook
End With

如果您想坚持使用 运行从 Outlook 中调用宏,请尝试像这样更改您的代码

' First line in Excel you want the copied data to go
Dim ExcelCount As Integer
ExcelCount = 1

For i = 1 To myfolder.Items.Count
Set myitem = myfolder.Items(i)
   ' Only copy data from unread items
   If myitem.UnRead = True Then
      xlobj.Range("a" & ExcelCount).Value = myitem.ReceivedTime
      xlobj.Range("b" & ExcelCount).Value = myitem.Subject
      xlobj.Range("c" & ExcelCount).Value = myitem.Importance
      xlobj.Range("d" & ExcelCount).Value = myitem.SenderName

      ' After copying the information, mark item as read
      myitem.UnRead = False

      ' Increase Excel line count
      ExcelCount = ExcelCount + 1
   End If
Next

您可能会发现 How to automate Outlook from another program 文章很有帮助。本文概述了使用另一个程序的自动化对 Outlook 进行编程。