【发布时间】:2015-10-16 14:09:53
【问题描述】:
我对编码有点陌生,但这里是 :)
我收到了需要使用 Excel 工作表中的信息以特定名称格式保存的电子邮件附件。
- 包含我需要的信息的行可以通过电子邮件的主题行来识别。
我想为 Outlook 中选定的电子邮件编写一些代码来执行以下操作:
- 使用电子邮件的主题行查找包含所需信息的行
- 从该行中的多个字段返回值
- 使用这些值和主题行来创建文件名
- 将文件保存到指定目录
我设法找到并重写了一些复制的代码,以仅使用主题行作为文件名来保存附件。我正在努力从 Excel 表中获取信息以将其附加到文件名中。
到目前为止,这是我的代码:
Sub SaveAttachments()
Dim objOL As Outlook.Application
Dim objMsg As Outlook.MailItem
Dim objAttachments As Outlook.Attachments
Dim objSelection As Outlook.Selection
Dim i As Long
Dim lngCount As Long
Dim strFile As String
Dim strFolderpath As String
Dim strFileName As String
Dim objSubject As String
Dim strDeletedFiles As String
strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16)
On Error Resume Next
' Instantiate an Outlook Application object.
Set objOL = CreateObject("Outlook.Application")
' Get the collection of selected objects.
Set objSelection = objOL.ActiveExplorer.Selection
' Set the Attachment folder.
strFolderpath = "C:\Users\User\Documents\"
' Check each selected item for attachments.
For Each objMsg In objSelection
'Set FileName to Subject
objSubject = objMsg.Subject
Set objAttachments = objMsg.Attachments
lngCount = objAttachments.Count
If lngCount > 0 Then
' Use a count down loop for removing items
' from a collection. Otherwise, the loop counter gets
' confused and only every other item is removed.
For i = lngCount To 1 Step -1
' Get the file name.
strFileName = objSubject & ".pdf"
' Combine with the path to the Temp folder.
strFile = strFolderpath & strFileName
Debug.Print strFile
' Save the attachment as a file.
objAttachments.Item(i).SaveAsFile strFile
Next i
End If
Next
ExitSub:
Set objAttachments = Nothing
Set objMsg = Nothing
Set objSelection = Nothing
Set objOL = Nothing
End Sub
我猜我需要编写一个函数来返回 Excel 工作表中的值,但我不知道该怎么做。
【问题讨论】:
-
在 Excel 而不是 Outlook 中实际执行此操作可能更容易(从语法角度来看)。在任何一种情况下,如果另一个应用程序正在运行,您都需要获取它的实例 - 如果不是,则创建应用程序的实例 - 以访问它的属性和方法。
-
@MacroMan 基于
CreateObject函数调用,看起来 OP 正在 从 Excel 执行此操作,绑定 到 Outlook 应用程序 :) -
@DavidZemens (d'oh) - 有时我会惊讶于自己在这些帖子中不阅读了多少……:$
标签: excel vba outlook email-attachments