我要做的就是打开一个.xlsm文件,运行一个宏,保存工作簿,然后退出。理想情况下,我可以将宏作为变量传递,因为不同的情况将运行位于同一工作簿中的不同宏。这是目前为止的代码。
import os, sys
import win32com.client
location = input("AOC or LOC")
macroBook = 'C:/path/to/workbook/solar.xlsm'
macro = 'solar.xlsm!Module1.Tag' + location
try:
if os.path.exists(macroBook):
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename=macroBook)
xl.Application.Run(macro) #Getting the error at this line
xl.Application.Save()
xl.Application.Quit()
del xl
except:
print("Unexpected error:" sys.exc_info()[0])我终于让宏运行了,但是当宏完成后,我仍然会得到相同的错误。这对我来说是一个很大的进步,因为在我无法让宏运行之前,这个程序对我来说是无用的,如果它只是在宏完成后出错的话。
所以我现在甚至不知道要排除什么问题。宏运行,但我被困在与宏没有运行时相同的线上。我以前有64位版本,这就是导致问题的原因,但是我已经切换到32位python了。
会不会是因为宏需要2-4分钟才能运行而导致错误?也许它不是在等它完成吗?我不知所措。如果需要的话,也愿意发布我的宏。
编辑:我删除了Application.Save行。代码现在看起来如下所示。
import os, sys
import win32com.client
location = input("AOC or LOC")
taggedData = 'C:/path/to/new/file.csv'
macroBook = 'C:/path/to/workbook/solar.xlsm'
macro = 'solar.xlsm!Module1.Tag' + location
try:
if os.path.exists(macroBook):
conn = win32com.client.Dispatch('ADODB.Connection')
conn.CommandTimeout = 3600
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename=macroBook)
xl.Application.Run(macro) #Getting the error at this line
for sheet in xl1.Worksheets:
if sheet.Name == "Sheet1":
nwb = xl.WorkbookAdd()
sheet.Copy(Before=nwb.Sheet(1))
nwb.SaveAs(taggedData)
nwb.Close(True)
xl.Application.Quit()
del xl
except:
print("Unexpected error:" sys.exc_info()[0])现在,我在conn.Open()上得到了一个名称错误。不确定这应该如何实现。
发布于 2016-03-07 15:28:08
我敢肯定你的COM接口已经超时了。我在处理py /excel的数据库时遇到了类似的错误.尝试添加一个命令超时,如下所示:
conn = win32com.client.Dispatch('ADODB.Connection')
conn.CommandTimeout = 3600否则,如果您只使用Excel / Python,那么如果您使用xlwing lib,那么所有的COM接口和运行时垃圾都会顺利地处理。我给您留下一个例子,并建议导入xlwing.。
假设您有这样的宏设置:
Sub my_macro()
RunPython ("import my_module; my_module.my_macro()")
End Sub用Python编写这个文件:
import os
from xlwings import Workbook, Range
def my_macro():
wb = Workbook.caller()
Range('A1').value = 1
# Now basically add whatever you want right here
if __name__ == '__main__':
# Expects the Excel file next to this source file, adjust accordingly.
path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'myfile.xlsm'))
Workbook.set_mock_caller(path)
my_macro()使用上面的cource代码结构,将您想要的任何内容放入my_macro():
否则,文档就在这里,而且很简单:http://xlwings.org/。
https://stackoverflow.com/questions/35846577
复制相似问题