在 Word 中从 VBA 创建和保存 Excel 文档

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

Creating and saving Excel document From VBA in Word

vbaword-vba

提问by Andrew

I want to be able to run a macro in a Word document that will create an Excel document and then save that spreadsheet in a shared folder.

我希望能够在 Word 文档中运行一个宏,该宏将创建一个 Excel 文档,然后将该电子表格保存在共享文件夹中。

This is the code I have so far:

这是我到目前为止的代码:

Public Sub Monthly_Commission_Extract()

Dim objExcel
Dim objDoc
Dim objSelection
Dim SaveAs1 As String
SaveAs1 = ("\stnlinasshd01\P403759\Month End\Monthly Commission Extractst Save")

Set objExcel = CreateObject("Excel.Application")
Set objDoc = objExcel.Workbooks.Add

objExcel.Visible = True

Set objSelection = objExcel.Selection

ActiveWorkbook.SaveAs FileName:=SaveAs1, FileFormat:=-4158, CreateBackup:=False
Application.DisplayAlerts = True

End Sub

The code is giving me an error:

代码给了我一个错误:

Run-time error '424': Object required

运行时错误“424”:需要对象

At the following piece of code:

在以下代码段中:

ActiveWorkbook.SaveAs FileName:=SaveAs1, FileFormat:=xlText, CreateBackup:=False

Please advise how I get around this.

请告知我如何解决这个问题。

回答by Tim Williams

objExcel.ActiveWorkbook.SaveAs 

not just

不只是

ActiveWorkbook.SaveAs 

Anything which "belongs" to Excel must be prefixed with your objExcelapplication reference.

“属于”Excel 的任何内容都必须以您的objExcel应用程序引用作为前缀。