因此,经过反复试验和谷歌搜索,我想出了以下解决方案,它非常适合我的目的。首先,在我的用户窗体上单击 F7 后,我将项目添加到列表数组中。
Private Sub UserForm_Initialize()
'Creates and assigns the array to ListBoxClients when the form loads
With ListBoxClients
.AddItem "Client 1"
.AddItem "Client 2"
.AddItem "Client 3"
End With
End Sub
然后,我为我的“OK”命令创建了以下响应。首先,它提示用户选择要处理的文件并打开第一个文件:
Private Sub cmdOK_Click()
Me.Hide
MsgBox "Click OK to browse and select files to exclude.", vbInformation
Dim MyDialog As FileDialog, GetStr(1 To 3000) As String '3000 files is the maximum applying this code
On Error Resume Next
Set MyDialog = Application.FileDialog(msoFileDialogFilePicker)
With MyDialog
.Filters.Clear
.Filters.Add "All WORD File ", "*.docx", 1
.AllowMultiSelect = True
i = 1
If .Show = -1 Then
For Each stiSelectedItem In .SelectedItems
GetStr(i) = stiSelectedItem
i = i + 1
Next
i = i - 1
End If
Application.ScreenUpdating = False
For j = 1 To i Step 1
Set Doc = Documents.Open(FileName:=GetStr(j), Visible:=True)
Windows(GetStr(j)).Activate
然后,我循环遍历数组中的选定项目,并用相同的文本替换每个选定的项目,颜色为红色(所以我的其他宏 - 此处未显示 - 在执行查找和替换时将跳过它) :
'Find and replace listbox items in files
Dim ii As Integer
For ii = 0 To ListBoxClients.ListCount - 1
If ListBoxClients.Selected(ii) Then
Selection.Text = ListBoxClients.List(ii)
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
Selection.Find.Replacement.Font.Color = 192
With Selection.Find
.Text = Selection.Text
.Replacement.Text = Selection.Text
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
在我完成之前,我删除了由于未知原因粘贴在每个文件顶部的选定数组项:
' delete mysterious added text at top of page (figure this out later)
Selection.HomeKey Unit:=wdStory
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Selection.Delete Unit:=wdCharacter, Count:=1
End If
Next ii
然后我有一些代码可以关闭当前文档并将其返回到 sub 的顶部以打开下一个文件(并最终结束)。我不知道为什么“Application.Run macroname:="NEWMACROS" 在那里,但它有效,所以我不打算删除它。
Application.Run macroname:="NEWMACROS"
ActiveDocument.Save
ActiveWindow.Close
Next
Application.ScreenUpdating = True
End With
End Sub
最后,如果用户改变主意,我添加取消表单的代码:
Private Sub cmdCancel_Click()
'User has cancelled so hide the form
Me.Hide
End Sub
就是这样。我希望这对其他人有帮助。