2017-08-27 151 views
-1

我有兩個工作簿,工作簿A和工作簿B.工作簿B使用SQL連接抓取數據,對數據執行一些計算(篩選),然後使用Public Sub稱爲Calculate123。在工作簿B的工作簿B中運行工作簿A

我想從工作簿A中打開工作簿B,在工作簿B上運行Calculate123,將結果發送到工作簿A,然後關閉工作簿B,而無需看到工作簿B打開。

此代碼將打開工作簿B,但不顯示它並刷新連接數據。

如何指導工作簿B從工作簿A運行Calculate123?我嘗試使用Applications.Run變體 - 這些都打開了新窗口。我試圖呼叫,運行在工作表A.

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 
+1

您是否*嘗試瞭解'Application.Run'可能用於什麼? –

+0

「我嘗試使用Applications.Run變體 - 這些都打開了新窗口。」如果您顯示您的非工作代碼,我們可能會幫助您解決問題。 (這可能就像從「應用程序」的末尾刪除「s」一樣簡單!)但是隻是顯示一條評論,指出「Run Sub code goes here?」並不能幫助我們發現錯誤。 – YowE3K

+0

或者它可能不是從'Applications.Run'中刪除一個字符,而是需要添加2個字符並刪除9個字符 - 但是很難確定沒有看到您嘗試的代碼。 – YowE3K

回答

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" 
+0

我的天啊,謝謝!我知道這是可能的,我的語法並不好,知道我在什麼範圍內,等等。 – Laizhensil

相關問題