从Excel 2011创建Word文件 [英] Create Word file from Excel 2011

查看:127
本文介绍了从Excel 2011创建Word文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

Set WD = CreateObject("Word.Document")

与Excel 2011一起运行时导致错误.

results in an error when run with Excel 2011.

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

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

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

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

推荐答案

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

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.

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

您可以交换两个Set word语句,这似乎是可取的,因为在PC上运行时无需进行错误代码处理,但是由于某些原因,该代码随后在Mac上运行得非常慢.

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.

这篇关于从Excel 2011创建Word文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆