运行时错误 '4218' 类型不匹配 ,简单又复杂的问题。
设计思路 :创建一个新WORD文档A,将模板WORD文档b的数据拷贝到A,并且在A中定位指定字符(比如“普通地热水洗井循环时间”),找到后在此后插入数据
问题:在做定位的时候出错。出错地方,代码为
---------------出错处 begin 类型不匹配--------
Set myRange = objWord.Range(Start:=0, End:=objWord.ActiveWindow.Selection)
---------------出错处 end 类型不匹配 --------
请问错在哪啊 ?
代码如下:
Sub btnWorkSummaryNew()
'打开的Excel文件路径
Dim strCurPath As String
'新生成的文件名称
Dim strFileName As String
Dim objWordApp As Word.Application
Dim objWord As Word.Document
Dim objWordTemplate As Word.Document
Dim objSel As Word.Selection
Dim myRange As Word.Range
strFileName = Trim(Sheets(strSheetInputName).Range("B5").Value) & "_" & Trim(Sheets(strSheetInputName).Range("A9").Value) & "_" & Format(Now, "yyyymmdd")
'关闭宏提示
Application.DisplayAlerts = False
Set objWordApp = CreateObject("Word.Application")
' Set objWordApp = New Word.Application
'查看 Documents 集合以判定名为“TemplateWord.doc”的文档是否已打开。如果该文档包含在 Documents 集合中,则激活该文档;否则,打开该文档。
For Each doc In objWordApp.Documents
If doc.Name = "TemplateWord.doc" Then Found = True
Next doc
If Found <> True Then
' objWordApp.Documents.Open FileName:=ThisWorkbook.Path & "\TemplateWord.doc"
Set objWordTemplate = objWordApp.Documents.Open(ThisWorkbook.Path & "\TemplateWord.doc")
Else
objWordApp.Documents("TemplateWord.doc").Activate
End If
Set objWord = objWordApp.Documents.Add
objWord.Application.Visible = True
objWord.SaveAs ThisWorkbook.Path & "\" & strFileName & ".doc"
strFileName = ThisWorkbook.Path & "\" & strFileName & ".doc"
'将模板数据拷贝到新建WORD文档中
With objWordTemplate 'Documents(2) 模板
'.Paragraphs.Last.Range.Select
'.Range.WholeStory
.Range(0).Select
.ActiveWindow.Selection.Copy
End With
With objWord.ActiveWindow.Selection 'Documents(1).ActiveWindow.Selection 生成的文档
.StartOf Unit:=wdStory, Extend:=wdMove
.Paste
End With
'Documents(strFileName).Activate
'Sales.doc must exist and be open but not active.
'Documents("Sales.doc").Activate
'objWordApp.Documents("TemplateWord.doc").Activate
'objWordApp.Documents(1).Activate
objWord.Activate
' If objWordApp.Documents.Count >= 1 Then
' MsgBox objWordApp.ActiveDocument.Name
' Else
' MsgBox "No documents are open"
' End If
'遍历新生成的文档,定位到“普通地热水洗井循环时间”,在其后加入
'Set myRange = objWord.Range(Start:=0, End:=Selection.End) 错误的参数号或无效的属性赋值
'Set myRange = objWordApp.ActiveDocument.Range(Start:=0, End:=Selection.End) 错误的参数号或无效的属性赋值
'Set myRange = objWord.Range(Start:=0, End:=200) 类型不匹配
'Set myRange = objWordApp.ActiveDocument.Range(Start:=0, End:=objWord.ActiveWindow.Selection) 类型不匹配
---------------出错处 begin 类型不匹配--------
Set myRange = objWord.Range(Start:=0, End:=objWord.ActiveWindow.Selection)
---------------出错处 end 类型不匹配 -------- For Each aWord In myRange.Words
If aWord.Text = "普通地热水洗井循环时间" Then
aWord.InsertAfter "New text "
Else
MsgBox "No Found"
End If
Next aWord
'
' Documents("TemplateWord.doc").Close SaveChanges:=wdDoNotSaveChanges
'
' objWord.Close
' objWordApp.Quit
End Sub
[解决办法]
对象定义错误!
[解决办法]
50%的结贴率会让人蛋疼的,你下次来看帖子可能不知猴年马月,说了可能也帮不到你,改为意外路过...