VBA报错:narDocument为String类型不支持Quit方法,求原因
问题分析:VBA中Word.Document对象异常变为String导致Runtime Error 438
问题描述
执行VBA代码里的narDocument.Quit False语句时触发错误:“Runtime Error 438: Object doesn't support this object or method”。经检查,narDocument的类型变为8(String类型),而字符串没有.Quit方法。尽管已将narDocument声明为Word.Document类型,且其余代码运行正常,但找不到对象被覆盖为字符串的原因。
相关代码
Public Sub testing_1() Dim narApplication As Word.Application Dim narDocument As Word.Document Set narApplication = CreateObject("word.application") Set narDocument = narApplication.Documents.Open(ThisWorkbook.Path & "/document_template.docx") MsgBox VarType(narDocument) Dim TITLE As String Dim myRange As Word.range Dim myFind As Word.Find Dim filePath As String TITLE = range("B1") 'For each value, find it's value in the blankdocument Set myRange = narDocument.Content Set myFind = myRange.Find With myFind .Text = "__TITLE__" searchResult = .Execute End With MsgBox VarType(narDocument) narDocument.Hyperlinks.Add Anchor:=myRange, Address:="http://www.google.com", TextToDisplay:=TITLE filePath = ThisWorkbook.Path & "/document_test.docx" narDocument.SaveAs2 Filename:=filePath MsgBox VarType(narDocument) ' Cleanup narDocument.Quit False Set narApplication = Nothing Set narDocument = Nothing End Sub
原因分析
- 方法调用错误:
.Quit是Word.Application对象的方法,用于关闭整个Word应用程序;Word.Document对象没有.Quit方法,对应的关闭方法是.Close。 - 对象被隐式覆盖:部分Word版本中,
SaveAs2方法执行后会返回保存后的文件路径字符串。如果代码中误将narDocument重新赋值为SaveAs2的返回值(即使未显式写Set),VBA会隐式将原本的Document对象覆盖为字符串类型,这就解释了后续VarType(narDocument)返回8的现象。
解决方案
- 修正关闭操作:将清理部分的
narDocument.Quit False替换为以下两种操作之一:- 仅关闭文档:
narDocument.Close SaveChanges:=wdDoNotSaveChanges - 关闭整个Word应用程序:
narApplication.Quit False
- 仅关闭文档:
- 避免对象被覆盖:确保
SaveAs2调用不会意外覆盖narDocument。如果不需要获取新的文档对象,直接执行narDocument.SaveAs2 Filename:=filePath即可;若需要获取保存后的文档对象,需用Set关键字:Set narDocument = narDocument.SaveAs2(Filename:=filePath)
内容的提问来源于stack exchange,提问作者user18349414
相关产品推荐
相关产品推荐

