如何使用此宏来查找&替换多个文件和文本框内的文本?

时间:2016-11-29 12:29:00

标签: vba replace ms-word macros ms-office

我有很多.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

这个新代码的唯一问题是,有时它会跳过一些文本框,而且它也有点慢。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

在VBA,Word&#34;文本框&#34;被称为TextFrame对象。这可能会指出你正确的方向:

For Each s In ActiveDocument.Shapes 
 With s.TextFrame 
 If .HasText Then MsgBox .TextRange.Text 
 End With 
Next

当我获得有关在您的示例中实现它的更多信息时,我将更新我的答案。