我正在尝试使用python在Personal.XLSB中运行一个宏。
当我自己从excel工作簿中运行宏PERSONAL.XLSB!PIVOTS时,它工作了。另外,如果我将vba代码复制并粘贴到“此工作簿”中,然后运行xlApp.Run('Pivots'),它就能正常工作。
但是,当我使用xlApp.Run('C:\\Users\\AppData\\Roaming\\Microsoft\\Excel\\XLSTART\\PERSONAL.XLSB!Pivots')时,它不会工作。我需要它在'PERSONAL.XLSB‘中运行,因为我将在几个文件中使用相同的宏。
from __future__ import print_function
import unittest
import os.path
import win32com.client
class ExcelMacro(unittest.TestCase):
def test_excel_macro(self):
try:
xlApp = win32com.client.DispatchEx('Excel.Application')
xlsPath = os.path.expanduser('C:\\Users\\colm_mcsweeney\\Documents\\Attachments\\Dash.09.05.19.xlsm')
wb = xlApp.Workbooks.Open(Filename=xlsPath)
xlApp.Visible = True
xlApp.Run("C:\\Users\\AppData\\Roaming\\Microsoft\\Excel\\XLSTART\\PERSONAL.XLSB!Pivots")
wb.Save()
xlApp.Quit()
print("Macro ran successfully!")
except:
print("Error found while running the excel macro!")
xlApp.Quit()
if __name__ == "__main__":
unittest.main()发布于 2020-10-15 23:07:15
诀窍是首先打开您的PERSONAL.XLSB文件,然后您可以打开/激活任何其他Excel wb并运行宏
import win32com.client
from pathlib import Path
# Folder I want to save the file to
folder = Path(r"C:\Users\user_name\folder")
# Your excel file you want to run the macro on
filename = excel.xlxs
save_path = folder / filename
# Sets up Excel to run Macro
try:
xl = win32com.client.Dispatch('Excel.Application')
xl.visible = False
personal_wb = xl.workbooks.Open(
Filename=r"C:\Users\user_name\AppData\Roaming\Microsoft\Excel\XLSTART\PERSONAL.XLSB")
wb = xl.workbooks.Open(Filename=save_path)
xl.Run("'PERSONAL.XLSB'!MyMacro")
wb.Close(SaveChanges=1)
xl.Quit()
print("Macro ran successfully")
except:
print("Error found while running the excel macro")
xl.Quit()我在网上查找了XLSTART的路径。有些人在本地,我的在漫游。
在excel中,您可以从PERSONAL.XLSB运行此宏,以获取您的文件路径
Sub Find_Personal_Macro_Workbook()
Dim path As String
path = Application.StartupPath
MsgBox path
End Subhttps://stackoverflow.com/questions/56073498
复制相似问题