VBA:使用 Excel 编辑 Word 文档会出现运行时错误 438:对象不支持此属性或方法



尽管谷歌搜索了很多,但我无法弄清楚这有什么问题。我是否仍然错过了参考资料或其他东西?如果你能看到错误在哪里,我将永远感激不尽!

引用:

  • Visual Basic for Applications
  • Microsoft Excel 16.0 对象库
  • OLE 自动化
  • Microsoft Office 16.0 对象库
  • 引用编辑控件
  • Microsoft Word 16.0 对象库

变量:

Public appWord As Word.Application
Public sapmWord As Word.Document
Dim asNimi As String 'in this current sub

法典:

On Error Resume Next
Set appWord = GetObject(, "Word.Application")
If Err <> 0 Then
Set appWord = CreateObject("Word.Application")
End If
On Error GoTo 0
appWord.Visible = True
Set sapmWord = appWord.documents.Open("C:ThisIsWorkingandDocOpens.docx")
'sapmWord.Activate 'doesn't make a difference
With sapmWord
Selection.EndKey Unit = wdStory 'this line is first line to give an error. With or without a dot in the beginning of line.
Selection.TypeText Text:=asNimi 'this line too, if previous is commented
'...and so on!
End With
sapmWord.Close savechanges:=True
Set appWord = Nothing
Set sapmWord = Nothing

sapmWord是一个word文档。Word 文档没有selection方法。Word 应用程序对象具有它,所以可能是您的意思(是的,您需要"."(

With appWord 
.Selection.EndKey Unit:= wdStory 
.Selection.TypeText Text:=asNimi 
'...and so on!
End With

你必须更改 sapmWord.Close savechanges:=True for appWord.quit savechanges:=True

要使用With,必须引用带有.的成员:

With sapmWord
.Selection.EndKey Unit = wdStory
.Selection.TypeText Text:=asNimi
End With

最后,我别无选择,只能将书签添加到Word文档中并用VBA填充它们。我仍然不知道为什么这些原始代码在我的代码中不起作用,尽管它们适用于其他人。谢谢大家的帮助,也许其他人在这里得到答案。

最新更新