替换所有子文件夹中word文件中的文本
Posted
技术标签:
【中文标题】替换所有子文件夹中word文件中的文本【英文标题】:Replace text in word file in all sub folders 【发布时间】:2013-05-30 06:56:02 【问题描述】:我正在整理一个 VBA 宏:
1.读取文件夹
2.创建其所有子文件夹的集合
3.遍历所有子文件夹,找到任何以.doc结尾的word文档
4.在每个.doc文件中:替换一些文本并保存然后关闭文档。
此宏无法正常工作:它不会替换子文件夹中任何 Word 文档中的文本。 它实际上并没有打开任何word文档,我不确定它是否应该一个接一个地打开每个word文档,或者它是否在后台运行。
Sub DoLangesNow()
Dim file
Dim path As String
Dim strFolder As String
Dim strSubFolder As String
Dim strFile As String
Dim colSubFolders As New Collection
Dim varItem As Variant
' Parent folder including trailing backslash
'YOU MUST EDIT THIS.
strFolder = "G:\2009\09771\Design\ESD\Commercial Tower KSD1\Green Star As Built\Round 1 Submission - Draft\02. Indoor Environment Quality"
' Loop through the subfolders and fill Collection object
strSubFolder = Dir(strFolder & "*", vbDirectory)
Do While Not strSubFolder = ""
Select Case strSubFolder
Case ".", ".."
' Current folder or parent folder - ignore
Case Else
' Add to collection
colSubFolders.Add Item:=strSubFolder, Key:=strSubFolder
End Select
' On to the next one
strSubFolder = Dir
Loop
' Loop through the collection
For Each varItem In colSubFolders
' Loop through word docs in subfolder
'YOU MUST EDIT THIS if you want to change the files extension
strFile = Dir(strFolder & varItem & "*.doc")
Do While strFile <> ""
Set file = Documents.Open(FileName:=strFolder & _
varItem & "\" & strFile)
' Start of macro 1replace text GS-XXXAB with GS-1624AB
'
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Application.WindowState = wdWindowStateNormal
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "GS-XXXAB "
.Replacement.Text = "GS-1624AB "
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
' End of macro 1
' Saves the file
ActiveDocument.Save
ActiveDocument.Close
' set file to next in Dir
strFile = Dir
Loop
Next varItem
End Sub
【问题讨论】:
【参考方案1】:您的代码通过以下更改为我工作
发件人strFile = Dir(strFolder & varItem & "*.doc")
到
strFile = Dir(strFolder & varItem & "\" & "*.doc")确保
strFolder
变量中的文件夹路径正确。例如(strFolder = "C:\Users\Santosh\Desktop\tes\
")
【讨论】:
以上是关于替换所有子文件夹中word文件中的文本的主要内容,如果未能解决你的问题,请参考以下文章