我之前发布过关于让我的 VBScript 等到进程完成后再继续(更多信息:VBScript - How to make program wait until process has finished?.
经过一番讨论,我得到了充分的答复。但是,我现在似乎正朝着代码的新方向前进,因为解决方案提出了另一个问题,我希望你能帮助我。
基本上我有一些我在下面提供的代码。它接受 4 个参数,其中一个是包含许多文件的文件夹的路径,我想在 VBA 宏中与其他三个一起使用这些文件。
If WScript.Arguments.Count = 4 Then
' process input argument
Set args = WScript.Arguments
arg1 = args.Item(0)
arg2 = args.Item(1)
arg3 = args.Item(2)
arg4 = args.Item(3)
' Create a WshShell instance
Dim WShell
Set WShell = CreateObject("WScript.Shell")
' Create an Excel instance
Dim x1
Set x1 = CreateObject("Excel.Application")
' Disable Excel UI elements
x1.DisplayAlerts = False
x1.AskToUpdateLinks = False
'x1.AlertBeforeOverwriting = False
x1.FeatureInstall = msoFeatureInstallNone
' Open the Workbooks specified on the command-line
Dim x1WB
Dim x2WB
Dim x3WB
Dim x4WB
Dim strWB1
Dim strWB2
Dim strWB3
Dim strWB4
Dim FSO
Dim FLD
Dim FIL
Dim strFolder
strWB1 = arg1
Set x1WB = x1.Workbooks.Open(strWB1)
' Show the workbook/Excel program interface. Comment out for silent running.
x1WB.Application.Visible = True
strWB2 = arg2
Set x2WB = x1.Workbooks.Open(strWB2)
' Show the workbook/Excel program interface. Comment out for silent running.
x2WB.Application.Visible = True
strWB3 = arg3
Set x3WB = x1.Workbooks.Open(strWB3)
' Show the workbook/Excel program interface. Comment out for silent running.
x3WB.Application.Visible = True
'To hold the string of the PATH to the multiple files
strFolder = arg4
Set FSO = CreateObject("Scripting.FileSystemObject")
'Get a reference to the folder I want to search
set FLD = FSO.GetFolder(strFolder)
Dim strMyMacro
strMyMacro = "my_excel_sheet_with_vba_module.xlsm!Sheet1.my_vba_macro"
'loop through the folder and get the file names
For Each Fil In FLD.Files
WshShell.run """C:\Program Files\Microsoft Office\Office14\EXCEL.exe"" " & Fil, 1, true
x1.Run strMyMacro
'~~> Problem - How do I get the macro to run before opening the above file but run after it has opened (due to setting the bWaitOnReturn to true)
'~~> Problem - How do I get the file on current iteration to close after the macro has completed?
'~~> Problem - If this is not the issue, can you identify it?
Next
x1WB.close
x2WB.close
x3WB.close
'x4WB.close
' Clean up and shut down
Set x1WB = Nothing
Set x2WB = Nothing
Set x3WB = Nothing
Set x4WB = Nothing
Set FSO = Nothing
Set FLD = Nothing
x1.Quit
Set x1 = Nothing
Set WshShell = Nothing
WScript.Quit 0
Else
WScript.Quit 1
End If
该脚本的工作方式如下:
- 4 个参数被传递给脚本。第三个参数是一个.xlsm文件,其中包含我的 VBA 宏。最后一个参数是包含多个文件的文件夹的路径。
- 然后它会打开前三个 Excel 文件。
- 然后我运行一个循环来遍历
Fil
指定为第四个参数的文件夹中的文件。AFAIK 这必须通过WScript.shell
使用该.run
方法来完成,以便脚本的其余部分将挂起,直到它正在处理的 Excel 文件完成,然后关闭它并打开文件夹中的下一个文件。 - 打开文件后
Fil
,我运行宏(尽管此时没有成功)。
我很想使用该对象简单地打开所有 Excel 文件,WScript.shell
但是我无法以这种方式运行宏。
希望我能够定义这段 VBScript 的目标,但如果我没有让我知道,我会澄清一下。你能帮我吗?
谢谢,QF。