在VBA Excel的dos命令中运行7Z会导致警告警报

时间:2012-07-06 09:35:46

标签: vba warnings alert 7zip

我目前正在使用以下代码从dos运行VBA命令,如下所示。

Set objShell = CreateObject("WScript.Shell")

dos_command="\\\10.xx.xx.xx\test\7z.exe  a -r " etc etc etc

result = objShell.Run(dos_command, 0, True)

Set objShell =nothing

一切运行良好,唯一的问题是我得到一个恼人的警告Windows Box建议程序试图在我的电脑上运行,按确定或取消

我必须使用"objshell",因为我需要VBA等待DOS命令完成。

有没有办法避免警告框从VBA中出现或向DOS命令添加一些其他参数?

7z.exe文件在服务器(不是本地PC)中运行,所以我认为这就是问题所在。

我不能在每台机器上使用或安装7z.exe。

2 个答案:

答案 0 :(得分:2)

以下是三个选项,按照从最快/最脏到最强大的顺序显示:

  1. 创建一个文本文件作为命令行的一部分并等待其存在:将命令行修改为类似的内容并使用Shell(而非objShell运行它1}}):

    dos_command = "\\\10.xx.xx.xx\test\7z.exe  a -r " etc etc etc
    dos_command = dos_command & " && echo > " & TempFileName
    

    这将在您的7-zip代码完成后创建一个名为TempFileName 的文本文件。您只需确保在运行shell命令之前TempFileName不存在,然后运行该命令并等待TempFileName文件存在。

  2. 使用OpenProcessGetExitCodeProcess API :使用OpenProcess API调用启动命令行,该调用可提供对新进程的访问权限(请注意Shell函数返回已启动进程的ProcessID)。然后使用ProcessID进入循环并通过GetExitCodeProcess轮询该过程。相关声明:

    Private Declare Function OpenProcess Lib "kernel32" _
            (ByVal dwDesiredAccess As Long, _
             ByVal bInheritHandle As Long, _
             ByVal dwProcessId As Long) As Long
    Private Declare Function GetExitCodeProcess Lib "kernel32" _
            (ByVal hProcess As Long, _
             lpExitCode As Long) As Long
    Private Const STILL_ACTIVE = &H103
    Private Const PROCESS_QUERY_INFORMATION = &H400
    
    '---------------------------------------------------------------------------------------vv
    ' Procedure : ShellWait
    ' DateTime  : 2/15/2008 10:59
    ' Author    : Mike
    ' Purpose   : Executes a shell command and waits for it to complete.
    ' Notes     : Runs the shell as a batch file, allowing the user to pass a string with
    '             line breaks to execute a multi-line command.
    '
    '           : Provides two means to break out of the loop.
    '             1) Provide a timeout in seconds.
    '                The code breaks out once it reaches the timeout.
    '             2) Provide a flag to tell the procedure to stop running.
    '                To use this option, you would need to pass the procedure a global flag
    '                that the user has the ability to change through the interface.
    ' Update (5/23/2008):
    '           - Uses a progressive sleep timer to allow fast processes to run quickly
    '               and long processes to get increasing clock cycles to work with.
    '           - Changed default window mode to hidden.
    '---------------------------------------------------------------------------------------
    '^^
    Public Function ShellWait(DosCmd As String, _
                              Optional StartIn As String = "WINDOWS TEMP FOLDER", _
                              Optional WindowStyle As VbAppWinStyle = vbHide, _
                              Optional TimeOutSeconds As Long = -1, _
                              Optional ByRef StopWaiting As Boolean = False)    'vv
        On Error GoTo Err_ShellWait
    
        Dim hProcess As Long, RetVal As Long, StartTime As Long
        Dim BatName As String, FileNum As Integer, SleepTime As Long
    
        StartTime = Timer
    
        BatName = TempFileName(StartIn, "bat")
        FileNum = FreeFile()
        Open BatName For Output As #FileNum
        ChDrive Left(BatName, 1)
        ChDir Left(BatName, InStrRev(BatName, "\"))
        Print #FileNum, DosCmd
        Close #FileNum
    
        hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, False, Shell(BatName, WindowStyle))
        SleepTime = 10
        Do
            'Get the status of the process
            GetExitCodeProcess hProcess, RetVal
            DoEvents: Sleep SleepTime
            If TimeOutSeconds <> -1 Then
                If Timer - StartTime > TimeOutSeconds Then Exit Do
            End If
            If StopWaiting Then Exit Do
            'Progressively increase the SleepTime by 10%
            '  This allows a quick process to finish quickly, while providing
            '  a long process with increasingly greater clock cycles to work with
            SleepTime = SleepTime * 1.1
        Loop While RetVal = STILL_ACTIVE
        Kill BatName
    
    Exit_ShellWait:
        Exit Function
    Err_ShellWait:
        MsgBox Err.Description
        Resume Exit_ShellWait
    End Function
    
    '---------------------------------------------------------------------------------------vv
    ' Procedure : TempFileName
    ' DateTime  : 12/9/08
    ' Author    : Mike
    ' Purpose   : Returns an unused file name but does not create the file.  Path can be
    '             passed with or without the trailing '\'.
    ' Requires  : TempPath() function
    '---------------------------------------------------------------------------------------
    '^^
    Function TempFileName(Optional ByVal Path As String = "WINDOWS TEMP FOLDER", _
                          Optional Ext As String = "txt", _
                          Optional Prefix As String = "temp") As String    'vv
    Dim TempFName As String, i As Integer
    
        If Path = "WINDOWS TEMP FOLDER" Then Path = TempPath
        If Right(Path, 1) <> "\" Then Path = Path & "\"
        If Not (Path Like "?:\*" Or Path Like "\\*") Then
            Err.Raise 52    '"Bad file name or number."
        ElseIf Dir(Path, vbDirectory) = "" Then
            Err.Raise 76    '"Path not found."
        End If
    
        TempFName = Path & Prefix & "." & Ext
        For i = 1 To 500
            If Dir(TempFName) = "" Then
                TempFileName = TempFName
                GoTo Exit_TempFileName
            End If
            TempFName = Path & Prefix & "_" & Format(i, "000") & "." & Ext
        Next i
        TempFileName = ""
    
    End Function
    
    '---------------------------------------------------------------------------------------
    ' Procedure : TempPath
    ' Author    : Mike
    ' Date      : 8/12/2008
    ' Purpose   : Returns something like:
    '               C:\DOCUME~1\BGRAND~1\LOCALS~1\Temp\
    '---------------------------------------------------------------------------------------
    '^^
    Function TempPath() As String    'vv
    Const TemporaryFolder = 2
    Static TempFolderPath As String
    Dim fs As Object
        If Len(TempFolderPath) = 0 Then
            Set fs = CreateObject("Scripting.FileSystemObject")
            TempFolderPath = fs.GetSpecialFolder(TemporaryFolder) & "\"
        End If
        TempPath = TempFolderPath
    End Function
    
  3. 使用CreateProcess和WaitForSingleObject API :请参阅此CreateProcess

  4. 帮助页面中的“超级Shell”示例

答案 1 :(得分:1)

调用Microsoft® Windows® Script Host会导致窗口显示该消息。而是试试这个

Public Sub test()
   Dim dos_command$, lRet&
   dos_command = """\\xxx.xxx.xxx.xxx\xxx\xxx\7z.exe"" a test.zip ""\\xxx.xxx.xxx.xxx\xxx\xxx\*.log"" -r"
   lRet = Shell(dos_command, vbMaximizedFocus)
   MsgBox lRet
End Sub

<强>更新

您可以执行以下操作并使用您的代码:

  • 打开开始|运行并输入gpedit.msc。单击“确定”
  • 用户配置&gt;&gt;管理模板&gt;&gt; Windows组件&gt;&gt;附件管理员
  • 将7z.exe添加到包含列表中以设置中等风险文件类型。

Hpe this help