在excel VBA中保存word docx文件为txt,得到运行时错误438



我试图将word docx文件保存为使用excel VBA的txt。然而,错误438出现时,我试图保存为新的字符串

Sub SaveToTXT()
Dim wordDoc As Object
Set wordDoc = CreateObject("Word.Application")

Dim wordPath As String

wordPath = "C:Usersfile"

wordDoc.Documents.Open wordPath

wordDoc.Visible = False

wordPath = Replace(wordPath, ".docx", ".txt")

wordDoc.SaveAs2 (wordPath)

wordDoc.Quit
End Sub

当你刚接触VBA时,使用延迟绑定是一个坏主意,因为延迟绑定不会给你任何智能感知。设置对Ms word的引用,以便您可以获得完整的智能感知(在IDE中使用工具)。参考资料则要确保MS Word xx。X对象库被选中)。

下面的代码应该会让你更接近你想要的

Sub SaveToTXT()
Dim myword As Word.Application
Set myword = New Word.Application

Dim myPath As String

' change ##user## to you username
myPath = "C:Users##user##Documents"

Dim myDoc As Word.Document
Set myDoc = myword.Documents.Open(myPath)

myWord.Visible = False

myDoc.SaveAs2 Replace(myDoc.Name, ".docx", ".txt"), fileformat:=wdFormatText

myDoc.Close savechanges:=False

myword.Quit
Set myword = Nothing
End Sub

如果你是VBA的初学者,那么我也强烈建议你安装免费的神奇的Rubberduck插件,并注意代码检查。

相关内容

最新更新