vba 从 Excel 2011 创建 Word 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8139792/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 14:28:02  来源:igfitidea点击:

Create Word file from Excel 2011

vbaexcel-vba-macexcel-2011

提问by rolf

The usual approach to create a Word document from Excel VBA:

从 Excel VBA 创建 Word 文档的常用方法:

Set WD = CreateObject("Word.Document")

results in an error when run with Excel 2011.

使用 Excel 2011 运行时会导致错误。

Any idea how a Word document can be created in Excel 2011 with VBA?

知道如何使用 VBA 在 Excel 2011 中创建 Word 文档吗?

(I do not want to use AppleScript as I want the program to be able to run on PCs also.)

(我不想使用 AppleScript,因为我希望该程序也能够在 PC 上运行。)

回答by rolf

The following code, based on the suggestion by bretville, seems to work both on mac (tested on Excel2011) and on pc (tested on Excel2007) and can be run repetedly, thus allowing creation of multiple Word files. What is required for the code to work under Excel2011 (mac) vba is a means to test if Word already is running or not. The approach is perhaps not the most elegant, but it works.

以下代码基于 bretville 的建议,似乎在 mac(在 Excel2011 上测试)和 pc(在 Excel2007 上测试)上都有效,并且可以重复运行,从而允许创建多个 Word 文件。代码在 Excel2011 (mac) vba 下工作所需的是一种测试 Word 是否已在运行的方法。这种方法可能不是最优雅的,但它有效。

Dim word As Object
Dim doc As Object
On Error Resume Next
Set word = GetObject(, "word.application") 'gives error 429 if Word is not open
If Err = 429 Then
    Set word = CreateObject("word.application") 'creates a Word application
    Err.Clear
End If
word.Visible = True
Set doc = word.documents.Add

You may interchange the two Set word statements, which might seem preferable as no error code handling becomes necessary when run on pc, but the code for some reason then runs terribly slowly on the mac.

您可以互换两个 Set word 语句,这似乎更可取,因为在 pc 上运行时不需要处理错误代码,但是由于某种原因,代码在 mac 上运行得非常慢。

回答by DontFretBrett

For a PC I would do this:

对于PC,我会这样做:

Dim word As Object: Set word = CreateObject("word.application")
word.Visible = True
Dim doc As Object: Set doc = word.documents.Add