为不包含该宏的excel书运行excel宏

时间:2015-02-25 12:24:48

标签: excel excel-vba vba

我需要运行我的Excel文档中不存在的宏,如果可能的话,它会记录在另一个excel文档或另一个文件中。

我试图打开两本excel书籍,第一本包含该宏,第二本书不包含,当我运行该宏时,它说我的excel书不包含该宏。

Option Explicit
Dim x1App, x1Book, x2App, x2Book
dim fso
dim curDir
set fso = CreateObject("Scripting.FileSystemObject")
curDir = fso.GetAbsolutePathName(".")
set fso = nothing

Set x1App = CreateObject("Excel.Application")
Set x2App = CreateObject("Excel.Application")
'~~> Change Path here
Set x1Book = x1App.Workbooks.Open(curDir & "\test.xlsm", 0, true)
Set x2Book = x2App.Workbooks.Open(curDir & "\perf.csv", 0, true)
x1App.visible = true
x2App.visible = true
x1App.Run "MyMacro"
x2App.Run "MyMacro"
xlBook.Close
xlApp.Quit

Set xlBook = Nothing
Set xlApp = Nothing

WScript.Echo "Finished."

所以这里我的宏是在test.xlsm excel文件中,我想在perf.csv上运行它。

这样我就做不到了。还有其他办法可以做这种工作吗?

我还将宏导出到文件中,而不是将宏的内容复制到我的* .vbs脚本中直接从它们运行它也没有成功。

1 个答案:

答案 0 :(得分:0)

以下是代码的工作示例

Option Explicit

Dim x1App, x1Book, x2App, x2Book
dim fso
dim curDir
set fso = CreateObject("Scripting.FileSystemObject")
curDir = fso.GetAbsolutePathName(".")
set fso = nothing

Set x1App = CreateObject("Excel.Application")
Set x1Book = x1App.Workbooks.Open(curDir & "\macro_for_creating_charts")
Set x2Book = x1App.Workbooks.Open(curDir & "\agent_perf.csv")
'x1App.visible = true
x1App.Run "macro_for_creating_charts.xlsm!Macro4"
x1App.ActiveWorkbook.Close(False)
x1App.Quit