我想创建一个宏(在Excel中)来打开另一个excel工作表,执行查找替换,然后保存它。
我已经用这样的word文档实现了这个目标:
...
Dim wrdDoc As Word.Document
If wrdApp Is Nothing Then Set wrdApp = CreateObject("Word.Application")
Set wrdDoc = wrdApp.Documents.Open(TemplateFilePath)
...
Call WordReplace(wrdDoc,"a","b")
....
Private Sub WordReplace(wrdDoc As Word.Document, sFind As String, sReplace As String)
With wrdDoc.Content.Find
.Text = sFind
.Replacement.Text = sReplace
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute Replace:=wdReplaceAll
End With
End Sub
我粗略地试图在上面的代码中用“Excel”替换“Word”这个词无济于事。
请问我能指出正确的方向吗?
答案 0 :(得分:3)
你可以这样做:
Sub a()
Dim excDoc As Workbook
....
Set excDoc = Workbooks.Open("c:\mata.xls")
Call WordReplace(excDoc, "a", "b")
....
End Sub
Private Sub WordReplace(excDoc As Variant, sFind As String, sReplace As String)
Dim sht As Worksheet
For Each sht In excDoc.Worksheets
With sht
.Cells.Replace What:=sFind, Replacement:=sReplace, LookAt:=xlWhole, _
SearchOrder:=xlByRows, MatchCase:=True, SearchFormat:=False, _
ReplaceFormat:=False
End With
Next
End Sub