求一段VB(word宏)的代码,关于文件查找替换功能。

请高人指点一下如果写这段代码:

条件:可能会有文件夹三个(有可能只有其中一个或者两个),名称分别为:1,2,3。每个文件夹下有若干txt文件

达成效果:

1. 每个文件夹里txt文件的名称变成以文件夹名开头,
如:2\a.txt变成2\2a.txt

2.
替换文件夹1的txt:aaa -> xxx
替换文件夹2的txt:bbb -> yyy
替换文件夹3的txt:ccc -> zzz

想了很长时间没想出来,求助。

先发一个替换的宏给你试试:

Sub Replace()

Dim Message, Title, Default, MyValue, NeedReplace, MyReplace
Message = "请输入文件所在目录" ' Set prompt.
Title = "InputBox Demo" ' Set title.
Default = "c:\" ' Set default.
' Display message, title, and default value.
MyValue = InputBox(Message, Title, Default)

Message = "请输入需要被替换的词" ' Set prompt.
Title = "InputBox Demo" ' Set title.
Default = "aaa" ' Set default.
' Display message, title, and default value.
NeedReplace = InputBox(Message, Title, Default)

Message = "请输入替换之后的词" ' Set prompt.
Title = "InputBox Demo" ' Set title.
Default = "xxx" ' Set default.
' Display message, title, and default value.
MyReplace = InputBox(Message, Title, Default)

Dim MyFoundFiles(10000)
Dim MyFoundCount

With Application.FileSearch
.FileName = "*.txt"
.LookIn = MyValue
.Execute
MyFoundCount = .FoundFiles.Count
For i = 1 To .FoundFiles.Count
MyFoundFiles(i) = .FoundFiles(i)
Next i
End With

For i = 1 To MyFoundCount
Documents.Open FileName:=MyFoundFiles(i)
With Selection.Find
.Text = NeedReplace
.Replacement.Text = MyReplace
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchByte = True
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
Documents(MyFoundFiles(i)).Save
ActiveWindow.Close
Next i

End Sub
温馨提示:答案为网友推荐,仅供参考
第1个回答  2009-07-29
手动操作一下,录下来再适当调整一下就行了
第2个回答  2009-07-29
好好学,这个不难,动手才是硬道理
相似回答