您在一个问题上问的太多了,无法获得完整的答案。本站是供程序员互相帮助开发的。您的问题应该包含一些错误代码,以便更有经验的程序员可以解释您哪里出错了。
我了解到您对 Outlook VBA 感到不舒服。当我开始时,我买了一本强烈推荐的书,发现它非常无用。我是通过实验学习的。当我想了解新事物时,我仍然会尝试。我还在这里通读了 Outlook 问题和答案。有一些知识渊博的人回答问题。我发现不断加深对 Outlook 可以实现的功能的理解很有帮助,即使我不希望使用一些更奇特的功能。
您需要将完成的任务分解为小的子任务。如果您的子任务足够小,您可能会在搜索时找到相关的内容。我对您的任务的细分是:
- 允许用户识别要从中保存附件的 Outlook 文件夹。
- 允许用户识别要保存附件的光盘文件夹。
- 阅读 Outlook 文件夹,查找带有用户附件的电子邮件。
- 对于每封带有用户附件的电子邮件:
4(a) 将附件保存到光盘文件夹,
4(b) 从电子邮件中删除附件
4(c) 使用已删除附件的详细信息编辑电子邮件正文。
我将提供一些代码来帮助您开始子任务 1 和 3。您应该能够轻松找到子任务 2 的帮助。我将包括一些关于子任务 4(a)、4(b) 和 4(c) 的指导。
我原以为用户识别 Outlook 文件夹的最简单方法是让用户打开该文件夹,然后启动宏。这就是我所采取的方法。请将此代码复制到模块中,打开相应的 Outlook 文件夹并运行宏。我相信我已经包含了足够多的 cmets 来解释宏在做什么,但如有必要,请提出问题:
Option Explicit
Sub DemoSelectFolderFromEmail()
Dim Exp As Explorer
' VBA has two types of Folder: Outlook folders and disc folders.
' Since you will need access to disc folders, it is important to be clear
' which type you mean.
Dim FldrSrc As Outlook.Folder
Dim InxA As Long
Dim InxF As Long
Dim ItemCrnt As MailItem
' Get collection of emails selected by user.
Set Exp = Outlook.Application.ActiveExplorer
' Check that an email has been selected.
If Exp.Selection.Count = 0 Then
Call MsgBox("Please select an email then try again", vbOKOnly)
Exit Sub
ElseIf Exp.Selection.Item(1).Class <> olMail Then
Call MsgBox("Please select an email then try again", vbOKOnly)
Exit Sub
End If
' The parent of a selected email is the Outlook folder that contains it.
' In my view, this is the easiest way for the user to identify the source
' folder.
Set FldrSrc = Exp.Selection.Item(1).Parent
Debug.Print FldrSrc.Name
' FldrSrc.Items is a collection of the items in FldrSrc.
' Probably every itemn is a MailItem but I check to be sure.
' ReceivedTime and Subject are just two of the properties that you can access.
' If there are any attachments, I display their names.
' Note that for VBA, signatures and images count as attachments. You will need
' to add code to idetify these attachments if you do not want to save them.
For InxF = FldrSrc.Items.Count To 1 Step -1
With FldrSrc.Items(InxF)
If .Class = olMail Then
Debug.Print .ReceivedTime & " " & .Subject
If .Attachments.Count > 0 Then
For InxA = 1 To .Attachments.Count
With .Attachments(InxA)
Debug.Print " " & InxA & " " & .DisplayName
End With
Next
End If
End If
End With
Next
End Sub
SaveAsFile 是将附件写入光盘文件夹的方法。请注意,SaveAsFile 将覆盖任何现有的同名文件。如果相同的DisplayName 用于不同的附件,您将需要一些使名称唯一的系统。
您需要编辑电子邮件以删除附件,然后保存编辑后的电子邮件。
电子邮件可以有文本正文和/或 Html 正文和/或 RTF 正文。我从未见过 RTF 正文,因此您可能可以忽略它们。如果电子邮件同时包含文本和 Html 正文,则用户会看到 Html 正文。现在很少有电子邮件没有 Html 正文。您可能只需在 Html 正文的开头添加一个字符串即可逃脱,但您需要进行试验以确保外观令人满意。我可能更喜欢在正文部分的开头插入一个完整的 Html 字符串,控制背景颜色、字体颜色、字体大小和字体名称,以便插入文本的外观始终相同。