![](/img/trans.png)
[英]MS Word / VBA - how can I loop through the document and look for 2 strings to remove everything in between them?
[英]How to delete a ms-word document if it contains various phrases with VBA?
我是VBA的新手,我知道其中包含错误。
在MS-Word开发人员中,我想上一个目录,在所有* .docx文件中搜索多个字符串,如果* docx文件内存在任何字符串,我想删除该文件。
Sub loopFiles()
Dim fso As New FileSystemObject
Dim fil As File
Dim fold As Folder
Dim yourfolder As String
Dim UpOneDir As String
Set fold = fso.GetFolder(Application.ActiveWorkbook.Path)
For Each fil In fold.Files
UpOneDir = Left(fil.Path, Len(fil.Path) - Len(fil.Name) - 1 - Len(Split(Left(fil.Path, Len(fil.Path) - Len(fil.Name) - 1), "\")(UBound(Split(Left(fil.Path, Len(fil.Path) - Len(fil.Name) - 1), "\")))))
Sub FindIt()
Selection.HomeKey Unit:=wdStory
With Selection.Find
.ClearFormatting
.Text = "Aircraft Survey","Cc:","UTAS","Inserted in the word document is a pdf file"
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = True
Do While .Execute
If InStr(1, fil.Text, "Aircraft Survey","Cc:","UTAS","Inserted in the word document is a pdf file") > 0 Then
Application.Workbook.Open fil.Path
ActiveWorkbook.Close
fil.Delete True
End If
Loop
End With
End Sub
End Sub
这就是我要做的。 您可能需要通过注释掉oFile.Delete
并将其替换为MsgBox oFile.Name
以便它不仅删除文件。 一旦满意地找到了所需的文件,请使用delete命令。
Option Explicit
Sub loopFiles()
Dim oFso: Set oFso = CreateObject("Scripting.FileSystemObject") ' create FileSystemObject
Dim oFolder: Set oFolder = oFso.GetFolder(oFso.GetParentFolderName(ThisDocument.Path)) ' Set folder to the Parent of the folder containing this file
Dim oFile, oDocument, textVal, bFound
Dim TextValues: TextValues = Array("Aircraft Survey", "Cc:", "UTAS", "Inserted in the word document is a pdf file") ' create array of terms to check
For Each oFile In oFolder.Files
If Right(oFile.Name, 5) = ".docx" Then ' if file is a *.docx
Set oDocument = Documents.Open(oFile.Path) ' Open it
bFound = False ' Initialise
For Each textVal In TextValues ' check for each text value
With oDocument.Content.Find
.Text = textVal
.Forward = True
.Execute
If .Found = True Then ' if found then set bFound
bFound = True
Exit For ' and exit the loop, no need to keep looking
End If
End With
Next
oDocument.Close wdDoNotSaveChanges ' close file and don't save any changes
If bFound = True Then ' If the text was found in the file
oFile.Delete ' delete the file
End If
End If
Next
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.