【发布时间】:2017-12-29 05:52:25
【问题描述】:
美好的一天!我是 VBA 新手。我正在尝试借助一些在线可用的 VBA 脚本自动将电子邮件从 Outlook 导出到 Excel。我最终得到了 80% 的结果。请查看我使用的代码。在那,我还需要添加一些代码来导出邮件正文。有人请指导我。
Public WithEvents objMails As Outlook.Items
Private Sub Application_Startup()
Set objMails = Outlook.Application.Session.GetDefaultFolder(olFolderInbox).Items
End Sub
Private Sub objMails_ItemAdd(ByVal Item As Object)
Dim objMail As Outlook.MailItem
Dim strExcelFile As String
Dim objExcelApp As Excel.Application
Dim objExcelWorkBook As Excel.Workbook
Dim objExcelWorkSheet As Excel.Worksheet
Dim nNextEmptyRow As Integer
Dim strColumnB As String
Dim strColumnC As String
Dim strColumnD As String
Dim strColumnE As String
If Item.Class = olMail Then
Set objMail = Item
End If
strExcelFile = "d:\LocalData\Z018439\Desktop\MY\NX-AMO\Mail Export\export.xlsx"
On Error Resume Next
Set objExcelApp = GetObject(, "Excel.Application")
If Error <> 0 Then
Set objExcelApp = CreateObject("Excel.Application")
End If
Set objExcelWorkBook = objExcelApp.Workbooks.Open(strExcelFile)
Set objExcelWorkSheet = objExcelWorkBook.Sheets("Sheet1")
nNextEmptyRow = objExcelWorkSheet.Range("B" & objExcelWorkSheet.Rows.Count).End(xlUp).Row + 1
strColumnB = objMail.SenderName
strColumnC = objMail.SenderEmailAddress
strColumnD = objMail.Subject
strColumnE = objMail.ReceivedTime
If StrComp(strColumnB, "service_manager7@mail.nissan.co.jp", vbTextCompare) = 0 Then
objExcelWorkSheet.Range("A" & nNextEmptyRow) = nNextEmptyRow - 1
objExcelWorkSheet.Range("B" & nNextEmptyRow) = strColumnB
objExcelWorkSheet.Range("C" & nNextEmptyRow) = strColumnC
objExcelWorkSheet.Range("D" & nNextEmptyRow) = strColumnD
objExcelWorkSheet.Range("E" & nNextEmptyRow) = strColumnE
objExcelWorkSheet.Columns("A:E").AutoFit
objExcelWorkBook.Close SaveChanges:=True
End If
objExcelApp.Quit
Set objExcelApp = Nothing
Set objExcelWorkBook = Nothing
Set objExcelWorkSheet = Nothing
Set objMail = Nothing
End Sub
【问题讨论】:
-
VB.Net 是否使用
Set语句?我认为这仅在 VBA 中是必需的。 -
@YowE3K:不。
Set甚至在 VB.NET 中都不存在(或者至少在这种情况下不存在)。这应该用 VBA 标记。