1

我正在尝试写入启用宏的 excel 文件 (xlsm),然后运行一个取决于我的脚本正在写入的单元格的宏。为了清楚起见,我在 Windows 机器上,我不是管理员,我正在使用 python3.8.0

我有一个名为write.py的文件,在这个文件中,它将昨天的日期写入 A1 单元格,除非它是星期一,然后它写入星期五的日期。在它写入日期之后,我想运行一个使用该单元格/日期做某事的宏。

到目前为止,我可以写昨天的日期并且可以运行宏,但我不能在同一个文件中执行它们。我尝试从write.py文件中分离文件并执行宏,但这给了我同样的错误。

这是我的write.py文件的代码,该文件将昨天的日期写入 xlsm 文件的 A1 单元格:

from datetime import date
from datetime import timedelta
import openpyxl

path = "C:/Users/project/file.xlsm"

# loads the workbook into a var
book = openpyxl.load_workbook(path)
sheet = book["Sheet2"] # loads a specific sheet by name into a var
a1 = sheet['A1'] # loads a cell into a var

# testing
print(book.sheetnames)
print(a1.value)

# Get yesterdays date unless its a Monday then get Fridays date
today = date.today() 
if date.today().weekday() == 0: 
    yesterday = today - timedelta(days=today.weekday()) + timedelta(days=4, weeks=-1)
else:
    yesterday = today - timedelta(days = 1)

yestFormat = (yesterday.strftime("%x")) # formatting the date 

# setting the value of the A1 cell to the yesterFormat var
sheet.cell(row=1,column=1,value=yestFormat)
book.save(path)

# This file is supposed to run the macro
exec(open('runMacro.py').read())

这是应该运行宏的第二个文件的代码,我在write.py文件中也有这个代码,我遇到了同样的问题

import xlwings as xw

# loads the workbook into workbook var then loads a specific sheet into worksheet var
wb = xw.Book(r'C:/Users/project/file.xlsm')
wb.macro('test_macro')()
wb.save(r'C:/Users/project/file.xlsm')

当我运行带有注释掉的 exec 命令的write.py文件时,它可以工作并将日期写入单元格。所以我执行宏的方式有问题。我注意到如果 excel 文件已打开,那么write.py文件将不起作用,而runMacro.py文件在我运行时会打开 excel 文档。我认为这与它如何保存或打开有关,但我已经阅读了 xlwings 文档,并且我正在按照它所说的如何保存,所以我不确定。希望有更好的方法,谢谢反馈。

编辑:对不起,我忘了添加我得到的错误。出于隐私原因,我已更改文件路径,因此可能存在一些不一致之处。

Traceback (most recent call last):
  File "C:\Users\project\venv\lib\site-packages\xlwings\_xlwindows.py", line 466, in __call__
    return Book(xl=self.xl(name_or_index))
  File "C:\Users\project\lib\site-packages\xlwings\_xlwindows.py", line 156, in __call__  
    v = self._inner(*args, **kwargs)
  File "C:\Users\username\AppData\Local\Temp\gen_py\3.8\00020813-0000-0000-C000-000000000046x0x1x8.py", line 
39136, in __call__
    ret = self._oleobj_.InvokeTypes(0, LCID, 2, (13, 0), ((12, 1),),Index
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147352565), None)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\project\code\venv\lib\site-packages\xlwings\main.py", line 3873, in open
    impl = self.impl(name)
  File "C:\Users\project\venv\lib\site-packages\xlwings\_xlwindows.py", line 468, in __call__
    raise KeyError(name_or_index)
KeyError: 'sample.xlsm'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "c:/Users/project/test.py", line 35, in <module>
    exec(open('test2.py').read())
  File "<string>", line 4, in <module>
  File "C:\Users\username\venv\lib\site-packages\xlwings\main.py", line 547, in __init__        
    impl = app.books.open(fullname, update_links, read_only, format, password, write_res_password,
  File "C:\Users\username\venv\lib\site-packages\xlwings\main.py", line 3879, in open
    impl = self.impl.open(fullname, update_links, read_only, format, password, write_res_password,
  File "C:\Users\username\venv\lib\site-packages\xlwings\_xlwindows.py", line 484, in open      
    return Book(xl=self.xl.Open(fullname, update_links, read_only, format, password, write_res_password,    
  File "C:\Users\username\venv\lib\site-packages\xlwings\_xlwindows.py", line 66, in __call__   
    v = self.__method(*args, **kwargs)
  File "C:\Users\username\AppData\Local\Temp\gen_py\3.8\00020813-0000-0000-C000-000000000046x0x1x8.py", line 
39013, in Open
    ret = self._oleobj_.InvokeTypes(1923, LCID, 1, (13, 0), ((8, 1), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17)),Filename
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', "Excel cannot open the file 'sample.xlsm' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.", 'xlmain11.chm', 0, -2146827284), None)
4

0 回答 0