gpt4 book ai didi

python - 尝试运行宏时,Python 中不断出现 pywintypes.com_error

转载 作者:行者123 更新时间:2023-12-01 04:04:38 24 4
gpt4 key购买 nike

我想做的就是打开一个 .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() 处收到名称错误。不确定这应该如何实现。

最佳答案

我相当确定您的 COM 接口(interface)超时。我在从 py/excel 操作数据库时遇到了类似的错误...尝试添加命令超时,如下所示:

conn = win32com.client.Dispatch('ADODB.Connection')
conn.CommandTimeout = 3600

否则,如果您专门使用 Excel/Python,则使用 xlwings lib 可以顺利处理所有 COM 接口(interface)和运行时垃圾。我给你留了一个例子并建议导入xlwings。

假设您设置了如下宏:

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()

使用上面的源代码结构,将您想要的任何内容放入 my_macro():

否则,文档就在这里,而且很简单:http://xlwings.org/ .

关于python - 尝试运行宏时,Python 中不断出现 pywintypes.com_error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35846577/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com