通過VB查找并替換WORD文檔中的字符串
發表于:2007-07-14來源:作者:點擊數:
標簽:
作者:隨筆 基本要求:需安裝WORD Function WordReplace(FileName As String, SearchString As String, ReplaceString As String, Optional SaveFile As String = , Optional MatchCase As Boolean = False) As Integer On Error GoTo ErrorMsg '函數運行時
作者:隨筆
基本要求:需安裝WORD
Function WordReplace(FileName As String, SearchString As String, ReplaceString As String, Optional SaveFile As String = "", Optional MatchCase As Boolean = False) As Integer
On Error GoTo ErrorMsg '函數運行時發生遇外或錯誤,轉向錯誤提示信息
Dim wordApp As New Word.Application
Dim wordDoc As New Word.Document
Dim wordArange As Word.Range
Dim wordSelection As Word.Selection
Dim ReplaceSign As Boolean
Dim I As Integer
'判斷將要替換的文件是否存在
If Dir(FileName) = "" Then
'替換文件不存在
MsgBox "未找到" & FileName & "文件" '提示替換文件不存在信息
WordReplace = -2 '返回替換文件不存在的值
Exit Function '退出函數
End If
Set wordApp = CreateObject("Word.Application") '建立WORD實例
wordApp.Visible = False '屏蔽WORD實例窗體
Set wordDoc = wordApp.Documents.Open(FileName) '打開文件并賦予文件實例
Set wordSelection = wordApp.Selection '定位文件實例
Set wordArange = wordApp.ActiveDocument.Range(0, 1) '指定文件編輯位置
wordArange.Select '激活編輯位置
I = 0 '初始化替換次數值
ReplaceSign = True '初始化是否替換成功標志
Do While ReplaceSign
ReplaceSign = wordArange.Find.Execute(SearchString, MatchCase, , , , , , wdFindContinue, , ReplaceString, True) '查找并替換
'判斷查找并替換是否成功,如果成功替換次數值遞增1
If ReplaceSign = True Then
I = I + 1
End If
Loop
MsgBox "已完成對文檔的搜索并完成 " & I & " 替換。" '提示總替換次數
'如果替換成功,則提示是否保存
If I > 0 Then
'判斷是否需要另存
If Trim(SaveFile) <> "" Then
'需要另存
If Dir(SaveFile) = "" Then
wordDoc.SaveAs SaveFile '文件另存為……
Else
'咨詢是否替換文件,如果不替換則放棄本次操作,否則存在本次操作
If MsgBox("是否替換" & SaveFile & "文件?",
vbYesNo + vbQuestion, "替換") = vbYes Then
wordDoc.SaveAs SaveFile '文件另存為……
End If
End If
Else
If MsgBox("是否保存對" & SaveFile & "更改?", vbYesNo + vbQuestion, "保存") = vbYes Then
wordDoc.Save '保存在原文件中
End If
End If
End If
WordReplace = I '返回替換次數
wordDoc.Close '關閉文檔實例
wordApp.Quit '關閉WORD實例
Set wordDoc = Nothing '清除文件實例
Set wordApp = Nothing '清除WORD實例
Exit Function
ErrorMsg:
MsgBox Err.Number & ":" & Err.Description '提示錯誤信息
WordReplace = -1 '返回錯誤信息值
wordDoc.Close '關閉文檔實例
wordApp.Quit '關閉WORD實例
Set wordDoc = Nothing '清除文件實例
Set wordApp = Nothing '清除WORD實例
End Function
注意事項:單擊在菜單“工程”中的“引用”菜單項,彈出窗口,在列表框中選擇“Microsoft Word X Object Libaray“,單擊引用
在
VB6.0+Office
XP+
Windows測試通過
原文轉自:http://www.anti-gravitydesign.com