0
我有很多.doc和.docx文件,我想更改大多數重複的簡單文本。如何使用此宏在多個文件和文本框中查找和替換文本?
所以,我目前所面對的這個宏運行:
Option Explicit
Public Sub BatchReplaceAll()
Dim FirstLoop As Boolean
Dim myFile As String
Dim PathToUse As String
Dim myDoc As Document
Dim Response As Long
PathToUse = "C:\Files\"
'Error handler to handle error generated whenever
'the FindReplace dialog is closed
On Error Resume Next
'Close all open documents before beginning
Documents.Close SaveChanges:=wdPromptToSaveChanges
'Boolean expression to test whether first loop
'This is used so that the FindReplace dialog will'only be displayed for the first document
FirstLoop = True
'Set the directory and type of file to batch process
myFile = Dir$(PathToUse & "*.docx")
While myFile <> ""
'Open document
Set myDoc = Documents.Open(PathToUse & myFile)
If FirstLoop Then
'Display dialog on first loop only
Dialogs(wdDialogEditReplace).Show
FirstLoop = False
Response = MsgBox("Do you want to process " & _
"the rest of the files in this folder", vbYesNo)
If Response = vbNo Then Exit Sub
Else
'On subsequent loops (files), a ReplaceAll is
'executed with the original settings and without
'displaying the dialog box again
With Dialogs(wdDialogEditReplace)
.ReplaceAll = 1
.Execute
End With
End If
'Close the modified document after saving changes
myDoc.Close SaveChanges:=wdSaveChanges
'Next file in folder
myFile = Dir$()
Wend
End Sub
如果你唯一的更換簡單的文本它的工作。 我的問題是我如何使用它來搜索和替換文本框內?
在此先感謝。
編輯1:
嗯,我得到的東西的工作(至少目前如此)
我改變了這個:
With Dialogs(wdDialogEditReplace)
.ReplaceAll = 1
.Execute
End With
這一點:
With Dialogs(wdDialogEditReplace)
For Each myStoryRange In ActiveDocument.StoryRanges
With myStoryRange.Find
.Text = "ORIGINAL_TEXT"
.Replacement.Text = "MODIFIED_TEXT"
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll
End With
Do While Not (myStoryRange.NextStoryRange Is Nothing)
Set myStoryRange = myStoryRange.NextStoryRange
With myStoryRange.Find
.Text = "ORIGINAL_TEXT"
.Replacement.Text = "MODIFIED_TEXT"
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll
End With
Loop
Next myStoryRange
End With
這個新代碼唯一的問題是有時它跳過一些文本框,它也有點慢。有任何想法嗎?
我得到了一些工作看看主帖 – Azuen
我假設如果你把一個條款明確尋找'TextFrame'它不會跳過它們。問題在於它會進一步減慢你的代碼,最終導致你的過程。每次添加到循環中的檢查都會在迭代中創建更多時間。我從來不知道是一個好的優化者,可悲的是說:( – SalvadorVayshun