简体   繁体   English

用 Excel VBA 打开一个 Word 文档,添加一些数据并保存它(Word 文档)

[英]Open with Excel VBA a Word document, add some data and just save it (the Word document)

I'm opening a preexisting word document with Excel VBA and add some data to it and then I just want to save this file.我正在使用 Excel VBA 打开一个预先存在的 word 文档并向其中添加一些数据,然后我只想保存这个文件。 But when I run the Excel VBA macro the word "save as" window appears.但是当我运行 Excel VBA 宏时,会出现“另存为”窗口。

And that's not my aim.这不是我的目标。

The word document should just be saved... (like when you add some data to the word document by hand and then press CTRL+S) word文档应该只是保存...(例如当您手动将一些数据添加到word文档然后按CTRL + S)

If more details are needed let me know... And many thanks for your help in advance.如果需要更多详细信息,请告诉我......非常感谢您提前提供的帮助。

Now my code:现在我的代码:

Dim appWord As Word.Application
Dim document As Word.Document

Set appWord = CreateObject("Word.Application")

' the excel file and the word document are in the same folder
Set document = appWord.Documents.Add( _
ThisWorkbook.Path & "\Testfile.docx")

' adding the needed data to the word file
...

' in this following line of code I tried to do the correct saving... but it opens the "save as" window - I just want to save it automatically
document.Close wdSaveChanges = -1

'Close our instance of Microsoft Word
appWord.Quit

'Release the external variables from the memory
Set document = Nothing
Set appWord = Nothing
Set document = appWord.Documents.Add( _
ThisWorkbook.Path & "\Testfile.docx") 

You're not opening a document with this code, you're creating a new, unsaved, document from an existing one.您不是使用此代码打开文档,而是从现有文档创建一个未保存的新文档。 Change it to:将其更改为:

Set document = appWord.Documents.Open( _
ThisWorkbook.Path & "\Testfile.docx")

You're also missing a colon.您还缺少一个冒号。

document.Close wdSaveChanges:=-1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM