我有一个运行宏的EXCEL文件。 当我从Excel文件中运行该宏时,它的运行没有问题。 然而,我想每天打开它并自动运行宏。我知道除了Python之外还有其他的方法,但我想看看我是否能用PY脚本来实现这个目标。下面的PY脚本能够打开我想要的excel文件并启动宏。
import win32com.client as win32
import os, os.path
import win32com.client
#from pathlib import Path
excel = win32.DispatchEx("Excel.Application")
book = excel.Workbooks.Open(Filename=r'C:\Gov\ExcelFile.xlsm')
excel.Application.Run('ExcelFile.xlsm!Module1.MainMacro')
book.Save()
book.Close()
excel.Application.Quit()
然而,一旦宏运行,它就会停止,并给出以下错误。
它说运行时错误'-2146959355(80080005)'。服务器执行失败
当我在VBA代码上运行调试器时,它突出了这一行。Set OutApp = CreateObject("Outlook.Application") 在下面的代码中。(VBA脚本的内容比下面的多,但这是调试器在点击时显示的内容)。
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set rng = Nothing
Set rng = Sheets("BuildMain").Range("A1:E5000")
'You can also use a sheet name
'Set rng = Sheets("YourSheet").UsedRange
**Set OutApp = CreateObject("Outlook.Application")** 'THIS IS THE LINE THAT THE DEBUGGER HIGHLIGHTS.
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.To = "Email@addy.com"
.CC = ""
.BCC = ""
.Subject = "Subject"
.HTMLBody = RangetoHTML(rng)
.Send 'or use .Display
End With
On Error GoTo 0
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set OutMail = Nothing
Set OutApp = Nothing