vb操作word 问题
Option Explicit
Dim xlsApp As Excel.Application
Dim wrdApp As Word.Application
Private Sub Command4_Click()
Dim strfilename As String, strreplace As String, strin As String
strfilename = "1.dot"
strreplace = "@份号"
strin = "正式份号"
Call OpenWordAndReplaceChar(strfilename, strreplace, strin)
End Sub
Private Sub Form_Unload(Cancel As Integer)
'Clear the memory
Set xlsApp = Nothing
Set wrdApp = Nothing
End Sub
'******************************************************************************************************
'功能: 开启一个预先定义好的WORD模板并替换模板中指定的某个字符串
'调用: Call OpenWordAndReplaceChar("001.doc", "$1", "宝宝:)")
'参数:
FileName: WORD文件名称 , ReplacedStr: WORD中待替换的字符 , ReplacementStr: 程序中传递到WORD中的字符串
'组件: 在工程中引用OR Microsoft Word X.0 object library才能使用word.application
'作者: FlashAsp
'Q Q: 21792038
'日期: 2006-03-12
'******************************************************************************************************
Public Sub OpenWordAndReplaceChar(FileName As String, ReplacedStr As String, ReplacementStr As String)
Dim wordApp As New Word.Application
Dim wordArange As Word.Range
Dim wordSelection As Word.Selection
Dim ReplaceSign As Boolean
Dim i As Integer
FileName = App.Path & "\" & FileName
Set wordApp = CreateObject("Word.Application")
wordApp.Visible = True
wordApp.Documents.Open (FileName)
Set wordSelection = wordApp.Selection
'指定文件编辑位置
Set wordArange = wordApp.ActiveDocument.Range(0, 1)
'激活编辑位置
wordArange.Select
'初始化是否替换成功标志
If ReplacedStr <> " " And ReplacementStr <> "" Then
ReplaceSign = True
Do While ReplaceSign
ReplaceSign = wordArange.Find.Execute(ReplacedStr, , , , , , , wdFindContinue, , ReplacementStr, True) Loop
End If
'回到打印状态
wordApp.ActiveWindow.View.Type = wdPrintView
End Sub
-------------------------------------------------------
以上代码在VB6+word2003中测试通过,但在vb6+word2007中出现:
实时错误 -2147023113(800706f7)
对象'execute'的方法'find'失败
[解决办法]
word2003 换成 word2007 引用修改了吗?
[解决办法]
楼主,2003和2007的Execute方法是不一样,
2003的如下:
expression.Execute(FindText, MatchCase, MatchWholeWord, MatchWildcards, MatchSoundsLike, MatchAllWordForms, Forward, Wrap, Format, ReplaceWith, Replace, MatchKashida, MatchDiacritics, MatchAlefHamza, MatchControl)
2007的如下:
表达式.Execute(FindText, MatchCase, MatchWholeWord, MatchWildcards, MatchSoundsLike, MatchAllWordForms, Forward, Wrap, Format, ReplaceWith, Replace, MatchKashida, MatchDiacritics, MatchAlefHamza, MatchControl, MatchPrefix, MatchSuffix, MatchPhrase, IgnoreSpace, IgnorePunct)
我个人建议楼主换一个写法,按形参来传递内容,这样就可以保证版本的兼容性,代码示例如下:
ReplaceSign = wordArange.Find.Execute(FindText:=ReplacedStr, Wrap:=wdFindContinue, ReplaceWith:=ReplacementStr)