使用VBS在外部运行Excel宏无效

时间:2019-02-18 17:38:50

标签: excel vba vbscript

我有一个excel宏,可以将某些数据行添加到excel工作簿中的某些工作表中。我遇到的问题是,如果我从工作簿中运行宏,则所有宏都像超级按钮一样工作,但是当我尝试从外部运行宏时,我不是很幸运。

我正在使用以下VBS代码运行宏,但由于某些原因,它未按预期运行。我可以在资源管理器中看到打开了excel文件(通过新的修改日期),但是里面的工作表没有任何变化。

Dim WshShell
Set WshShell = CreateObject("WScript.Shell")

' 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

' Tell Excel what the current working directory is 
' (otherwise it can't find the files)
Dim strSaveDefaultPath
Dim strPath
strSaveDefaultPath = myExcelWorker.DefaultFilePath
strPath = WshShell.CurrentDirectory
myExcelWorker.DefaultFilePath = strPath

' Open the Workbook specified on the command-line 
Dim oWorkBook
Dim strWorkerWB
strWorkerWB = strPath & "\WatchlistMentoring.xlsm"

Set oWorkBook = myExcelWorker.Workbooks.Open(strWorkerWB)

' Build the macro name with the full path to the workbook
Dim strMacroName
strMacroName = "'" & strPath & "\WatchlistMentoring.xlsm!UpdateAllspreads()"
on error resume next 
   ' Run the calculation macro
   myExcelWorker.Run strMacroName
   if err.number <> 0 Then
      ' Error occurred - just close it down.
   End If
   err.clear
on error goto 0 

oWorkBook.Save 

myExcelWorker.DefaultFilePath = strSaveDefaultPath

' Clean up and shut down
Set oWorkBook = Nothing

' Don’t Quit() Excel if there are other Excel instances 
' running, Quit() will shut those down also
if myExcelWorker.Workbooks.Count > 0 Then
    myExcelWorker.Quit
    End If

    Set myExcelWorker = Nothing
    Set WshShell = Nothing

很明显,文件名和宏名称本身是正确的,但是不确定我是否一起使用它们都是正确的?

0 个答案:

没有答案