2015-12-15 111 views
2

我試圖刷新的Excel與下面的Python腳本文件:如何使Excel RefreshAll等待關閉直到完成?

xl = Dispatch('Excel.Application') 
workbook = xl.Workbooks.open('\\path\to\workbook.xlsx') 
xl.Visible = True 
workbook.RefreshAll() 
xl.Quit() 

然而,後臺查詢(連接到SQL數據庫),需要一段時間來刷新。

如何防止此電子表格在RefreshAll完成之前關閉?

+2

http://stackoverflow.com/questions/22083668/wait-until-activeworkbook-refreshall-finishes-vba –

+0

我覺得這就是一個重複:HTTP ://stackoverflow.com/questions/11832628/how-to-have-python-wait-until-an-excel-macro-refresh-is-done – wardw123

回答

1

對於「查詢」 &透視表,您可以通過每片&查詢/樞做到這一點,你總得循環**表後臺刷新設置爲False,因爲它是表本身的屬性(而不是在工作簿水平,說。)

**對於數據透視表,Python模塊中的數據透視表似乎不可迭代,所以相反,我基本上設置一個計數器(根據需要調整)以查看最大值(預期!)。每個工作表的數據透視表數量(我將它設置爲5)。 (假設索引從1開始連續向上,並且不能,比如說沒有數據透視表(1),但是有一個數據透視表(2))。如果這是假的,請糾正我的答案

for sheet in workbook.Sheets: 
    print(sheet.name) 
    for table in sheet.QueryTables: 
     print("Found a query table on %s called %s" % (sheet.name, table.name)) 
     table.BackgroundQuery = False # i.e.: disable background query, and therefore cause Excel to 'wait' until it's done refreshing 
     if table.Refresh() == True:  # This both refreshes the table, AND if the Refresh() method returns True (i.e.: refreshes successfully), tells you so. 
      print("Query table %s refreshed!" % table.name) 
     else: 
      print("Query table %s FAILED to refresh." % table.name) 
    for i in range(1,5): 
     try: 
      print("Found pivot table #%s called %s" % (i,sheet.PivotTables(i).Name)) 
      if sheet.PivotTables(i).RefreshTable()==True: 
       print("Refreshed pivot table %s" % sheet.PivotTables(i).Name) 
      else: 
       print("FAILED to refresh pivot table %s" % sheet.PivotTables(i).Name) 
     except: 
      print("No pivot table #%s found on sheet %s" % (i,sheet.Name)) 
      break # Break out of the for loop, since there's no point in continuing the search for pivots, I believe (but could be wrong about that! Try creating two pivots, then deleting the first. Does the second become PivotTables(1), or stay as 2?) 
+0

太棒了,謝謝! – codycrossley

+0

注:我還沒有想出如何爲數據透視表禁用後臺查詢刷新...不知道這是否會對您造成問題 – wardw123

+0

目前這不是問題,因爲我不需要數據透視表(現在至少)。我敢肯定,我最終必須研究它。再次感謝!如果我這樣做,我會嘗試你的數據透視表建議,並看看如何收費! – codycrossley