VBA代码删除由单词创build的临时文件

我有代码删除文件夹中的所有文件:

ChDir "C:\test\" 'path Kill "C:\test*.*" 'type 

但是,当我打开一个doc文件并将其保存为文本时,它会创build一个名为〜$ *****。doc的临时文件,这些文件不会被删除。

我将如何做到这一点?

 Sub BatchConvertCSV() 'declarations Dim i As Integer Dim j As Integer Dim NewName As String Dim objWord As Object Dim ApplicationFileSearch As New FileSearch Dim iCnt As Integer Set objWord = CreateObject("Word.Application") 'search for all.doc files in specified folder With ApplicationFileSearch .NewSearch .LookIn = "C:\test\" .SearchSubFolders = False .FileName = "*.doc" .Execute j = .FoundFiles.Count i = 1 MsgBox ("Found files " & j) 'open each document Do While i < j Set objWord = Documents.Open(FileName:=.FoundFiles(i)) With ActiveDocument iCnt = ActiveDocument.Fields.Count 'Somewhere here we need to decide on the placement for an if statement to filter out the doc files for 35 and 39 fields. 'If the doc file does not have that amount of fields 'MsgBox ("Found fields " & iCnt) If iCnt > 30 And iCnt < 40 Then .SaveFormsData = True 'save open file as just form data csv file and call it the the vaule of i.txt (ie 1.txt, 2.txt,...i.txt) and close open file NewName = i ChangeFileOpenDirectory "C:\test\Raw Data\" ActiveDocument.SaveAs FileName:=NewName objWord.Close False Else End If End With i = i + 1 Loop 'repeat to the ith .doc file End With ChDir "C:\test\" 'path Kill "C:\test\*.*" 'type 

尝试这个:

 With CreateObject("Scripting.FileSystemObject").getfolder("C:\Test") For Each file In .Files If Left(file.Name, 2) = "~$" Then Kill "C:\Test\" & file.Name End If Next file End With 

当然,您可以根据需要细化该filter。

我唯一可以看到的问题是,在循环浏览files ,您正在从.Files files删除files 。 它可能会工作,但将每个文件添加到列表可能更安全,而不是在ForEach循环中将其删除,然后通过并杀死列表中的所有内容。

编辑:多一点研究。 根据这篇文章 ,你不能在只读文件上使用Kill 。 这意味着您需要使用SetAttr命令删除“只读”标志。 以下是一些可能有所帮助的代码:

 Dim strDir, strFile As String strDir = "C:\Test\" 'Don't forget the trailing backslash strFile = Dir(strDir & "~$*", vbHidden) Do Until strFile = "" If Len(Dir$(strDir & strFile)) > 0 Then SetAttr strDir & strFile, vbNormal Kill strDir & strFile End If strFile = Dir() Loop 

正如你所看到的那样,包括在试图删除文件之前检查文件是否真实存在。 因为我们将这个文件与Dir拉起来,所以检查不应该是必要的,但是您的经验表明在这里需要额外的预防措施。 让我知道这是如何工作。