我有下面的代码,它一直有效,直到我提取附件后尝试移动文件。
错误表明该文件仍处于打开状态。当我尝试手动移动它时,我确认了这一点。
Filename = Dir(RFQFolder)
Set outApp = GetObject(, "Outlook.Application")
'Open .msg file in Outlook 2007+
Set outEmail = outApp.Session.OpenSharedItem(RFQFolder & Filename)
For Each outAttachment In outEmail.Attachments
If outAttachment.Filename Like "*.xls*" Then
ROUploadFile1 = RFQFolder & outAttachment.Filename
outAttachment.SaveAsFile RFQFolder & outAttachment.Filename
End If
Next
outEmail.Close olDiscard
Set outEmail = Nothing
Set outApp = Nothing
Set outAttachment = Nothing
Set oFS = CreateObject("Scripting.Filesystemobject")
oFS.moveFile Source:=RFQFolder & "" & Filename, Destination:=Newpath & "" & Filename
Set oFS = Nothing
如果移动文件是个问题,为什么不直接保存到需要的地方呢?
Filename = Dir(RFQFolder)
Set outApp = GetObject(, "Outlook.Application")
'Open .msg file in Outlook 2007+
Set outEmail = outApp.Session.OpenSharedItem(RFQFolder & Filename)
For Each outAttachment In outEmail.Attachments
If outAttachment.Filename Like "*.xls*" Then
ROUploadFile1 = RFQFolder & outAttachment.Filename
outAttachment.SaveAsFile Newpath & "" & Filename 'Changed the save path
End If
Set outAttachment = Nothing
Next
outEmail.Close olDiscard
Set outEmail = Nothing
Set outApp = Nothing
您正在访问Attachments
集合(outEmail.Attachments
(-您需要
- 将引用存储在专用变量中,并通过设置为
Nothing
来释放它 - 避免使用";对于每个";循环-它们保留对所有collciton项的引用
- 最简单的方法是将所有代码移动到一个单独的子中:这样,当子退出时,VBA将释放该子的所有内部变量。你可以在潜艇外呼叫
MoveFile