我有两个工作簿,工作簿A和工作簿B.工作簿B使用SQL连接抓取数据,对数据执行一些计算(过滤),然后使用名为Calculate123的Public Sub填充图表。
我想从工作簿A打开工作簿B,在工作簿B上运行Calculate123,将结果发送到工作簿A,然后在没有看到工作簿B打开的情况下关闭工作簿B.
此代码将打开工作簿B而不显示它并刷新连接数据。
如何指示工作簿B从工作簿A运行Calculate123?我尝试使用Applications.Run变体 - 这些都打开了新窗口。我试过Call,在工作表A中运行Sub。
Public Sub openExcel()
Dim xlApp As Excel.Application
Dim sourceWB As Excel.Workbook
Dim sourceWS As Excel.Worksheet
Dim updater As Range
Set xlApp = New Excel.Application
With xlApp
.Visible = False
.EnableEvents = False
'.UserControl = False
'.DisplayAlerts = False
.AskToUpdateLinks = False
End With
strFile = "S:\Service\KPI Project\Daily Numbers - John Doe.xlsm" 'Put your file path.
Set sourceWB = xlApp.Workbooks.Open(strFile, , False, , , , , , , True)
sourceWB.Activate
Set sourceWS = xlApp.ActiveSheet
sourceWB.RefreshAll
'this line is where the call would be. I tried the following combinations:
'Run.Application("'filepath'"!Calculate123)
'sourceWB.Call
'sourceWB.Run
'sourceWS.Call
'sourceWS.Run
'Run.Application("filepatch"!module8)
'xlApp.Run("'filepath'")
'xlApp.Run(Calculate123)
xlApp.DisplayAlerts = False
xlApp.Quit
'possible garbage cleaning? not sure
Set xlApp = Nothing
Set sourceWB = Nothing
Set sourceWS = Nothing
End Sub
答案 0 :(得分:0)
您说您尝试了以下命令:
Run.Application("'filepath'"!Calculate123)
'Would fail because "Run" won't have an "Application" method, and because the parameter
' to "Run" should be a string
sourceWB.Call
'Would fail because "sourceWB" is an object in the existing application and
' Workbooks don't have a "Call" method
sourceWB.Run
'Would fail because "sourceWB" is an object in the existing application and
' Workbooks don't have a "Run" method
sourceWS.Call
'Would fail because "sourceWS" is an object in the existing application and
' Worksheets don't have a "Call" method
sourceWS.Run
'Would fail because "sourceWS" is an object in the existing application and
' Worksheets don't have a "Run" method
Run.Application("filepatch"!module8)
'Would fail because "Run" won't have an "Application" method, and because the parameter
' to "Run" should be a string specifying the name of the subroutine
xlApp.Run("'filepath'")
'Would fail because the parameter to "Run" should be the name of the subroutine
xlApp.Run(Calculate123)
'Would fail because the parameter to "Run" should be a string
替换说
的行'Run Sub code goes here?
与
xlApp.Run "Calculate123"