通过python运行VBA代码时出错

时间:2018-07-12 10:36:25

标签: vba python-3.x

如何从此python脚本运行VBA宏?我连续两次运行该代码时遇到两个错误。

我的目标是

  1. 从sql server中提取数据(完成)
  2. 创建一个宏文件并运行 在提取的数据上
  3. 将所有内容另存为excel文件
  4. (python中的

我知道在vba代码或通过python访问文件中存在一些问题。我被卡住了!如果有人有经验或知识,请分享:)

每次运行的错误消息

# create pymssql connection and cursor
cnxn = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER='+server+';PORT=1443;DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()

# import and run sql query file
sql_file = os.path.realpath('****.sql')
sql_query = open(sql_file, mode='r', encoding='utf-8-sig')
df_sql = pd.read_sql(sql_query.read(), cnxn)

# save dataframe to .xlsx 
filename = '****' + date_today_filename + '.xlsx'
writer = pd.ExcelWriter(filename, engine='xlsxwriter')
df_sql.to_excel(writer, sheet_name='****', index=False)

# attach macro and create .xlsm file
filename_macro = '****' + date_today_filename + '.xlsm'
workbook = writer.book
workbook.filename = filename_macro
workbook.add_vba_project(os.path.realpath('vbaProject.bin'))
writer.save()


# reference file path and run macros
if os.path.exists(filename_macro):
    xl = win32com.client.Dispatch('Excel.Application')
    xl.Workbooks.Open(Filename = os.path.realpath(filename_macro), ReadOnly=1)
    xl.Application.Run("Macro1")
    #xl.Application.Run("Macro2")
    #xl.Application.Run("Macro3")
    xl.Application.Quit()
    del xl

PYTHON代码

var non_overlapping = dbCaptions.Captions.Any(x =>
x.MovieId == caption.MovieId &&( x.EntryTime < caption.EntryTime && x.ExitTime < caption.EntryTime || x.EntryTime > caption.EntryTime && caption.ExitTime < x.EntryTime )

0 个答案:

没有答案