使用Python(pywin32)或VBA在Excel中更改Microsoft Query

我需要从2014年4月1日至2015年3月31日的每个客户的个人销售(500人左右)的财政年度创build报告。去年,当我这样做时,我去了每一个报告从前一年,只是改变查询中的date,以便通过该财政年度。 但是,我们的客户群进一步增长,现在看起来我会花费几个小时这样做,除非我find了在后台更改查询的方法。

我可以浏览包含这些报告的文件夹中的每个工作表,并打开每个文件进行编辑:

import os, pythoncom from win32com.client import Dispatch for path, subdirs, files in os.walk("location\of\folder"): # Open each workbook for filename in files: xl = Dispatch("Excel.Application") wb = xl.Workbooks.Add(path+"\\"+filename) ws = wb.Worksheets(1) # Method to alter the query here!!!! # Would even be open to doing this with VBA and just calling a macro to run # change the query if that's possible?! wb.Close() xl.Quit() pythoncom.CoUninitialize() 

任何帮助,将不胜感激,因为它可能会节省我几个小时单调的工作时间。

非常感谢!

我刚刚尝试了下面的方法来尝试使用VBA更改SQL。

 Sub change_date() Sheets(1).Select ActiveSheet.QueryTables(1).CommandText = Replace(ActiveSheet.QueryTables(1).CommandText, "WHERE (Customers.InvoiceDate>={ts '2013-04-01 00:00:00'} And Customers.InvoiceDate<={ts '2014-03-31 00:00:00'})", "WHERE (Customers.InvoiceDate>={ts '2014-04-01 00:00:00'} And Customers.InvoiceDate<={ts '2015-03-31 00:00:00'})") End Sub 

但是我得到一个运行时(9)错误:下标超出范围。

任何帮助,将不胜感激。

我已经知道所有关心的人。

 Sub change_date() Dim sh As Worksheet, LO As ListObject, QT As QueryTable Set sh = ActiveSheet Set QT = sh.ListObjects.Item(1).QueryTable With QT .CommandType = xlCmdSql .CommandText = Replace(QT.CommandText, "WHERE (Customers.InvoiceDate>={ts '2013-04-01 00:00:00'} And Customers.InvoiceDate<={ts '2014-03-31 00:00:00'})", "WHERE (Customers.InvoiceDate>={ts '2014-04-01 00:00:00'} And Customers.InvoiceDate<={ts '2015-03-31 00:00:00'})") .Refresh End With End Sub