附加到电子邮件后删除文档

时间:2016-11-16 19:54:02

标签: vba ms-word word-vba

新手在这里。我已经使用“提交”按钮创建了一个启用宏的Word文档。该文档是只读的,所以我要做的就是保存临时文件,附加临时文件,然后删除它。很简单吧?一切正常,但它不会被删除。附件是“提交”按钮的代码。请帮忙!感谢。

Public Sub SubmitButton_Click()
Dim OL              As Object
Dim EmailItem       As Object
Dim Doc             As Document
Dim sTempFilePath   As String

Application.ScreenUpdating = False
sTempFilePath = ("C:\temp\test.doc")

Set OL = CreateObject("Outlook.Application")
Set EmailItem = OL.CreateItem(olMailItem)
Set Doc = ActiveDocument
ActiveDocument.SaveAs FileName:="C:\temp\test.doc"
With EmailItem
    .Subject = "Application For Leave Form"
    .To = "email@email.com"
    .Attachments.Add sTempFilePath
    .Send
End With

Application.ScreenUpdating = True
Set OL = Nothing
Set EmailItem = Nothing
Set Doc = Nothing
ActiveDocument.Close
Kill sTempFilePath

End Sub

为简单起见,我拿出了很多代码,但它仍然没有删除文件。这有什么不对?

Public Sub SubmitButton_Click()
Dim Doc             As Document
Dim sTempFilePath   As String

sTempFilePath = ("C:\temp\test.doc")

Set Doc = ActiveDocument

ActiveDocument.SaveAs FileName:="C:\temp\test.doc"

ActiveDocument.Close

Kill sTempFilePath

End Sub

2 个答案:

答案 0 :(得分:1)

使用FileSytemObject()对象制作所需文件的副本,最后将其删除

这是一个后期绑定的例子

Public Sub SubmitButton_Click()
    Dim sTempFilePath   As String

    sTempFilePath = ("C:\temp\test.doc")

    With CreateObject("Scripting.FileSystemObject") '<--| instantiate a running instance of 'FileSystemObject' object
        .CopyFile ActiveDocument.FullName, sTempFilePath '<--| copy active document into a new file
    End With

    '....code to process sTempFilePath

    Kill sTempFilePath '<--| and finally... kill it!

End Sub

答案 1 :(得分:0)

您可以将新文档作为副本添加到当前文档,并将该副本保存到所需位置。然后,一旦关闭文件,您将关闭新创建的文件并可以成功删除它。 这对我有用,希望对你有用。

请参阅代码段的代码:

Public Sub SubmitButton_Click()
Dim OL              As Object
Dim EmailItem       As Object
'Dim Doc             As Document   'not needed
Dim sTempFilePath   As String

Application.ScreenUpdating = False
sTempFilePath = ("C:\temp\test.doc")

Set OL = CreateObject("Outlook.Application")
Set EmailItem = OL.CreateItem(olMailItem)
'Set Doc = ActiveDocument ' not needed
Application.Documents.Add ActiveDocument.FullName
ActiveDocument.SaveAs FileName:="C:\temp\test.doc"
With EmailItem
    .Subject = "Application For Leave Form"
    .To = "email@email.com"
    .Attachments.Add sTempFilePath
    .Send
End With

Application.ScreenUpdating = True
Set OL = Nothing
Set EmailItem = Nothing
'Set Doc = Nothing
ActiveDocument.Close
Kill sTempFilePath

End Sub

将此应用于您的工作代码,您将拥有:

{{1}}

参考:http://www.vbaexpress.com/kb/getarticle.php?kb_id=961