2017-08-30 78 views
0

我已经写了Microsoft Word的VBA代码,当点击一个按钮时发送一封电子邮件。当按钮被点击,宏完成时,我想从桌面上删除文件。VBA杀死函数没有删除文件

当我现在运行此宏时,Microsoft Word将关闭,但该文件不会从我的桌面上删除。

这里是我的代码:

Private Sub CommandButton1_Click() 
Dim OL    As Object 
Dim EmailItem  As Object 
Dim Doc    As Document 
Dim FileName  As String 
Dim FilePath  As String 
Dim DeletePath  As String 

Application.ScreenUpdating = False 
Set OL = CreateObject("Outlook.Application") 
Set EmailItem = OL.CreateItem(olMailItem) 
Set Doc = ActiveDocument 
myFileName = "Form" 
FilePath = "C:\Users\" & Environ("Username") & "\desktop\" 
Doc.SaveAs2 FileName:=FilePath & myFileName & ".docx", Fileformat:=wdFormatXMLDocument, AddToRecentFiles:=False 
With EmailItem 
    .Subject = "Bid Award Form" 
    .Body = "Please Review the attached Bid Award form" 
    .To = "[email protected]" 
    .Importance = olImportanceNormal 'Or olImprotanceHigh Or olImprotanceLow 
    .Attachments.Add Doc.FullName 
    .Send 
End With 

    'display a message using named arguments 
MsgBox _ 
prompt:="Your email has been sent. Please check your Outlook sent mail for confirmation", _ 
Buttons:=vbOKOnly, _ 
Title:="Email Confirmation" 



'Close the File 
Doc.Close 

Kill "C:\Users\" & Environ("Username") & "\desktop\form.docx" 

'Close the Application of the document we are going to delete 
Application.Quit 

Application.ScreenUpdating = True 

Set Doc = Nothing 
Set OL = Nothing 
Set EmailItem = Nothing 



End Sub 

任何帮助,您可以提供将是非常有益的!

+0

你不能删除一个文件,是在我们自行尝试过这种子应用 – jsotola

回答

0

可能您正在查看错误的文件。 Kill是一个函数,它没有错误。 只需尝试以下操作:

Sub KillTheFile 
    Kill "C:\Users\" & Environ("Username") & "\desktop\form.docx" 
End Sub 

然后看看它是否有效。可能你有一个文件frm.docx或类似的文件。

+0

开放,并与提供的路径工作。只是在其他代码的上下文中,事情会变得混乱。 – noldak

+0

@noldak - 然后在'Kill'​​之前停下来,然后写'Application.ScreenUpdating = True'。然后再次按F5。你可能会很幸运。只是为了记录 - 任何机会,你的代码中的某处是否有'On Error Resume Next'? – Vityata

+0

我认为你可以将它粘贴到立即窗口(整个“kill ...”行),按回车键查看文件是否消失。如果没有,请尝试完整路径并查看它是否有效。这应该给你一些线索。 –

0

尝试像这样反而

On Error Goto 0 
Dim sDocName as string 
sDocName = Doc.FullName 
Doc.Close 
Kill sDocName