【发布时间】:2015-04-02 07:31:57
【问题描述】:
我有一个包含宏的 excel 文件。宏写在开发人员选项卡的 ThisWorkbook 中。我想通过在 Windows 任务调度程序中调度宏来自动运行宏。
我做了一些研究,发现我必须为此编写一个 vbscript 并运行 vb 脚本才能运行宏。
这是 vb 脚本。 vbscript 应该:
- 打开excel文件
- 运行宏
- 关闭excel文件
这应该每天使用 Windows 任务调度程序在预定时间自动完成。
到目前为止,这是 vb 脚本:
'Script to start my filter.xls program with named macro
'MsgBox "In RunExcel"
' Create an Excel instance
Dim myExcelWorker
Set myExcelWorker = CreateObject("Excel.Application")
' Disable Excel UI elements
myExcelWorker.DisplayAlerts = False
myExcelWorker.AskToUpdateLinks = False
myExcelWorker.AlertBeforeOverwriting = False
myExcelWorker.FeatureInstall = msoFeatureInstallNone
' Open the Workbook
Dim oWorkBook
Dim strWorkerWB
strWorkerWB = "C:\Users\Desktop\service calibration details\CC.xlsm"
'MsgBox "Opening filter"
on error resume next
Set oWorkBook = myExcelWorker.Workbooks.Open(strWorkerWB)
if err.number <> 0 Then
' Error occurred - just close it down.
MsgBox "open Error occurred"
End If
err.clear
on error goto 0
'MsgBox "Running macro"
Dim strMacroName
strMacroName = "CCA"
on error resume next
' Run the macro
myExcelWorker.Run strMacroName
if err.number <> 0 Then
' Error occurred - just close it down.
MsgBox "run macro Error occurred"
End If
err.clear
on error goto 0
' Clean up and shut down
Set oWorkBook = Nothing
myExcelWorker.Quit
Set myExcelWorker = Nothing
Set WshShell = Nothing
我尝试使用基于 microsoft windows 的脚本主机来运行它。但我收到错误“发生运行宏错误”。
我在互联网上搜索。但是我找不到解决方案。
是什么导致了这个问题?
我写的vbscript有错误吗?
我如何成功执行此操作?
【问题讨论】:
-
“发生错误”消息没有诊断价值。加
& " 0x" & Hex(Err.Number) & " " & CStr(Err.Number) & " " & Err.Description,你就可以得到更多信息来找到罪魁祸首。提示:Run方法启动一个在新 Windows 进程中运行的 程序... -
@JosefZ 我应该把它添加到哪里?
-
MsgBox "bla-bla Error occurred" & " 0x" & Hex(Err.Number) & " " & CStr(Err.Number) & " " & Err.Description。对于所有bla-bla:运行宏、打开、... -
@JosefZ 可以在代码中编辑吗?