使用 Excel VBA 打印 Word 文档而不打开它
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1419829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Print a Word document without opening it using Excel VBA
提问by nickjohn
I want to print a Word document, mydocument.docx, from a button in an Excel sheet. Both are in the same folder.
我想从 Excel 工作表中的按钮打印 Word 文档 mydocument.docx。两者都在同一个文件夹中。
I don't want users to see the Word document. They just click the button in Excel.
我不希望用户看到 Word 文档。他们只需单击 Excel 中的按钮。
I can create a button in Excel and make it open an empty vb. This is as much as I know. If you can explain this in steps that would be so awesome.
我可以在 Excel 中创建一个按钮并让它打开一个空的 vb。这就是我所知道的。如果你能分步骤解释这一点,那就太棒了。
回答by bobbymcr
You can use the Word automation object modelto gain programmatic access to Word.
您可以使用Word 自动化对象模型以编程方式访问 Word。
In almost all cases, you'd be following these steps:
在几乎所有情况下,您都将遵循以下步骤:
- Create the Word application object.
- Open a document.
- Do something with the document.
- Close the document.
- Quit the Word application.
- 创建 Word 应用程序对象。
- 打开一个文档。
- 对文档做一些事情。
- 关闭文档。
- 退出 Word 应用程序。
Here is what the basic VBA code looks like:
下面是基本的 VBA 代码:
' Step 1
Dim objWord
Set objWord = CreateObject("Word.Application")
' Hidden window!
objWord.Visible = False
' Save the original printer, otherwise you will reset the system default!
Dim previousPrinter
Set previousPrinter = objWord.ActivePrinter
objWord.ActivePrinter = "My Printer Name"
' Step 2
Dim objDoc
Set objDoc = objWord.Documents.Open("C:\Test\SomeDocument.docx")
' Step 3 -- in this case, print out the document without any prompts
objDoc.PrintOut
' Restore the original printer
objWord.ActivePrinter = previousPrinter
' Step 4
objDoc.Close
' Step 5
objWord.Quit

