如何成功执行vbscript?

问题描述:

我有一个包含宏的excel文件。该宏是在开发人员选项卡的ThisWorkbook中编写的。我想通过在Windows任务计划程序中安排它来自动运行宏。如何成功执行vbscript?

我做了一些研究,发现我必须为此编写一个vbscript并运行vb脚本才能运行宏。

这是vb脚本。应该VBScript的:

  1. 打开Excel文件
  2. 运行宏
  3. 关闭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 

我试图运行这个使用基于Windows脚本宿主。但我收到错误“运行宏错误发生”。

我在互联网上搜索。但我找不到解决办法。

是什么导致了这个问题?

在我写的vbscript中是否有错误?

我该如何成功执行此操作?

+2

“_error occurred_”消息没有诊断价值。加'&“0x”&十六进制(Err.Number)&“”&CStr(Err.Number)&“”&Err.Description“,那么你可以得到更多的信息来找到一个罪魁祸首。提示:'Run'方法在新的Windows进程中启动_program_运行... – JosefZ 2015-04-02 08:23:44

+0

@JosefZ我应该在哪里添加它? – adrian 2015-04-03 02:56:04

+1

'MsgBox“bla-bla发生错误”&“0x”&Hex(Err.Number)&“”&CStr(Err.Number)&“”&Err.Description'。对于所有'bla-bla':_run宏_,_open_,... – JosefZ 2015-04-03 03:00:35

作为这个问题的一种替代方法,您可以只有一个简单的VB脚本文件来打开电子表格。事情是这样的:

Set xl = CreateObject("Excel.application") 

xl.Application.Workbooks.Open "C:\Users\Desktop\service calibration details\CC.xlsm" 
xl.Application.Visible = True 

Set xl = Nothing 

然后把你的Excel宏进Workbook_Open子,以便打开工作簿时它执行。在宏的末尾添加行:

ActiveWorkbook.Close False 'false prevents it from saving any changes 
Application.Quit 

,或者如果你想保存

ActiveWorkbook.Save 
Application.Quit 

这样应该可以做的伎俩!祝你好运。