大家好, 我是 python 初學者, 目前使用 python 正在寫一個 xls2xlsx 程式, 但忽然想到有些 xls 裡有巨集存在, 不知道 python 要如何判斷 xls 裡有巨集?? 若 xls 有巨集則自動轉存成 xlsm
目前我是使用 win32com
我曾參考過這個文章 (
Python win32com模块操作Excel:VBA模块读写
)
會出現: 不信任以程式設計方式存取 Visual Basic 專案
不知道我錯在哪了
1.我是 office 2007
2.python 3.8.10, 模組全部更新到最新
3.已開啟信任中心的巨集設定: "啟用所有巨集"及勾選"信任存取VBA專案物件模型"
懇請各位幫忙
錯誤訊息:
R->D:\prg_python\test\test.xls
Traceback (most recent call last):
File "D:\prg_python\xlsVba.py", line 27, in <module>
vba = wb.VBProject.VBComponents.Count
File "C:\Users\user\AppData\Roaming\Python\Python38\site-packages\win32com\client\dynamic.py", line 628, in __getattr__
ret = self._oleobj_.Invoke(retEntry.dispid, 0, invoke_type, 1)
pywintypes.com_error: (-2147352567, '發生例外狀況。', (0, 'Microsoft Office Excel', '不信任以程式設計方式存取 Visual Basic 專案\n', 'C:\\Program Files (x86)\\Microsoft Office\\Office12\\1028\\XLMAIN11.CHM', 0, -2146827284), None)
測試用程式碼如下:
# python 3.8.1
# 自動版
import os
import sys
import win32com.client
from win32com.client import Dispatch
# 搜尋條件
import fnmatch
readDir =r"D:\prg_python\test"
writeDir = readDir
fileType = ["*.xls"]
xlsFile = "test.xls"
readFile = readDir + "\\" + xlsFile
w = win32com.client.Dispatch('Excel.Application')
w.Visible = 0
w.DisplayAlerts = 0
origin_val = w.Application.AutomationSecurity
w.Application.AutomationSecurity = 1
print("R->" + readFile )
wb = w.Workbooks.Open(readFile)
vba = 0
vba = wb.VBProject.VBComponents.Count
if vba == 0:
writeFile = readFile + "x"
wb.SaveAs(writeFile,FileFormat = 51)
print("W>>"+ writeFile)
else:
writeFile = readFile + "m"
wb.SaveAs(writeFile,FileFormat = 52)
wb.Close()
w.Application.AutomationSecurity = origin_val
w.Quit()# 退出
# 刪除舊檔
if vba == 0:
os.remove(readFile)
except OSError as e:
print(e)
else:
print("File is deleted successfully")
sys.exit(0)