WScript.Shell 崩溃 Excel

WScript.Shell crashes Excel

我正在使用 WshShell 运行 来自 VBA 的批处理文件 Excel。

有人知道最近的更新是否可以做到这一点吗?或者我可以使用的另一种方法?

潜艇是:

Public Sub RunBatch(FPath As String)
    Dim WinSh As Object
    Dim StrCmd As String
    Dim ErrCode As Long
    Set WinSh = New WshShell
    StrCmd = Chr(34) & FPath & Chr(34)
    ErrCode = WinSh.Run(StrCmd, WindowStyle:=1, WaitOnReturn:=True)
End Sub
  
Public Sub RunBatch2(FPath As String)
    Dim WinSh As Object
    Set WinSh = VBA.CreateObject("WScript.Shell")
    WinSh.Run FPath, 1, True
End Sub

问题的根源是 Cisco AMP 的安全策略更新或更改。这会阻止使用 Windows 脚本宿主。我所在组织的安全部门正在努力寻找问题的解决方案。

与此同时,我找到了解决方法。我使用 shell (在恢复 VBA 代码之前不等待批处理结束)到 运行 在过程结束时写入一个简单文本文件的批处理,我等待使文本文件以 1 秒为增量出现。它很粗糙,但到目前为止它有效。

Public Sub OneRunBatch()

Dim xlWB As Workbook
Dim fso1 As New FileSystemObject
Dim BatFile As Object
Dim IsDone As Boolean
Dim OutFileName As String
Dim DoneFileName As String
Dim OutPath As String
Dim DeleteBatFile As Boolean

Set xlWB = ThisWorkbook
OutPath = xlWB.Path
OutFileName = "HW.bat"
DoneFileName = "Done.txt"
DeleteBatFile = False

Set BatFile = fso1.CreateTextFile(OutPath & "\" & OutFileName)
BatFile.WriteLine "cd /d " & OutPath
BatFile.WriteLine "echo Hello World"
BatFile.WriteLine "dir > " & DoneFileName
BatFile.Close

IsDone = False
Call Shell(OutPath & "\" & OutFileName, vbNormalFocus)

Do Until IsDone
    If fso1.FileExists(OutPath & "\" & DoneFileName) Then IsDone = True
    Application.Wait (Now + TimeValue("00:00:01"))
Loop

fso1.DeleteFile (OutPath & "\" & DoneFileName)
If DeleteBatFile Then fso1.DeleteFile (OutPath & "\" & OutFileName)

End Sub