我正在尝试使用python在Personal.XLSB中运行宏。
当我从excel工作簿中自己运行宏 db.Colleges.aggregate([
{ "$match": { "clgID": { "$in": ["100", "200"] }}},
{ "$lookup": {
"from": "Subjects",
"localField": "clgID",
"foreignField": "college.collegeID",
"as": "clg"
}},
{ "$unwind": { "path": "$clg", "preserveNullAndEmptyArrays": true }},
{ "$group": {
"_id": { "clgId": "$clg.college.collegeID", "_id": "$_id" },
"groupDetails": { "$push": "$clg.members.student" },
"clgName": { "$first": "$name" }
}},
{ "$project": {
"_id": "$_id._id",
"clgName": 1,
"groupDetails": {
"$reduce": {
"input": "$groupDetails",
"initialValue": [],
"in": { "$concatArrays": ["$$this", "$$value"] }
}
}
}}
])
时,它将起作用。另外,如果我将vba代码复制并粘贴到“此工作簿”中并运行PERSONAL.XLSB!PIVOTS
,它将起作用。
但是,当我使用xlApp.Run('Pivots')
时,它将不起作用。我需要它在'PERSONAL.XLSB'中运行,因为我将在多个文件中使用相同的宏。
xlApp.Run('C:\\Users\\AppData\\Roaming\\Microsoft\\Excel\\XLSTART\\PERSONAL.XLSB!Pivots')
答案 0 :(得分:1)
诀窍是先打开您的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 Sub