【发布时间】:2019-02-14 05:06:45
【问题描述】:
当 Outlook 启动时,我需要在辅助电子邮件帐户中的文件夹上运行 VBA,以查看在我的计算机关闭期间是否有人将带有附件的电子邮件移到那里。我想保存附件。
我还有其他代码可以在 Outlook 运行时监视文件夹并保存附件。它还会在电子邮件中添加一条注释“文件已保存到 C:\Temp\TEST”。
当 Outlook 启动时,我想扫描文件夹中没有“文件已保存到 C:\Temp\TEST”文本的电子邮件,然后保存这些附件。
我知道脚本的保存/添加文本部分有效,但是,我明白了
“未设置对象变量或With Block”
在这一行:
If InStr(1, LCase(ItemCrnt.Body), LCase("The file(s) were saved to")) > 0 Then
我怀疑这一定是我定义变量的方式。
Private Sub Application_Startup()
Dim ns As Outlook.NameSpace
Dim olAccount As Outlook.Recipient
Dim olInbox As Outlook.Folder
Dim ItemCrnt As Object
Dim strFile As String
Dim strFolderpath As String
Set ns = Application.GetNamespace("MAPI")
Set olAccount = ns.CreateRecipient("xyz@mycompany.com")
olAccount.Resolve
Set olInbox = ns.GetSharedDefaultFolder(WLAccount, olFolderInbox)
Set ItemCrnt = olInbox.Folders("My Folder").Items
' First check the folders and make sure that any exisiting emails in the
folders have already had attachments saved to the strFolderpath
' Get the path to the folder
strFolderpath = "C:\Temp\TEST\"
' Check each selected item for attachments. If attachments exist,
' save them to the strFolderPath folder and add a note to the message with
the file path.
With ItemCrnt
' This code only saves attachments from mail items.
'If .Class = olMail Then
'Check if the attachments have already been saved
If InStr(1, LCase(ItemCrnt.Body), LCase("The file(s) were saved to")) > 0 Then
' ...code to save attachments and add text to body of message goes here...
End If
End If
End With
End Sub
【问题讨论】:
-
我相信在 Outlook 启动时,您的收件箱还没有真正“准备好”,所以 ItemCrnt 基本上是
Nothing,因此未设置错误对象变量块。可以尝试.OnTime来延迟该过程。如果我错了,请随时纠正我。 -
文件夹好像是空的。您可以添加条件以首先检查 Object
ItemCrnt是否为空。请注意,对象ItemCrnt是您文件夹中所有项目的数组,您不能在其中使用.Body,您首先需要引用数组中的某个对象,例如ItemCrnt(1).Body -
WLAccount 没有定义——你的意思是 olAccount 吗?还是应该删除 WLAAccount?两个没有 enuf IF-s 的 EndIf——取出一个?此外,您需要检查 ItemCrnt.Items.Count 以确定是否有任何项目。
-
您已将 ItemCrnt 设置为
olInbox.Folders("My Folder").Items,这是“我的文件夹”中项目的集合。像这样定义,ItemCrnt 没有 Body。您需要类似:For Each ItemCrnt in olInbox.Folders("My Folder").Items...Next。如果不清楚,我可以展开。 -
@TonyDallimore 感谢您指出这一点!这解决了我的问题。我还必须在 With 块之前移动 For Each 来搜索字符串,然后保存附件。