如何使用 VBA 执行 shell 命令?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2290365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 10:18:20  来源:igfitidea点击:

How can I execute a shell command using VBA?

windowsvbashell

提问by aF.

I want to execute a shell command like the following using Visual Basic for Applications.

我想使用 Visual Basic for Applications 执行如下所示的 shell 命令。

C:\Temp\gc.exe 1

How can I do it?

我该怎么做?

采纳答案by Jim Counts

Example:

例子:

 retVal = Shell("C:\Temp\gc.exe 1", vbNormalFocus)

Link: Shell Invoked from VBA

链接:从 VBA 调用的 Shell

回答by rchacko

This shows the scenarios where you want to call an exe file and pass an argument to it using shell command. The following code checks the folder where chrome.exe residing and calling www.google.com, from there (assuming you installed chrome) by passing url as argument:

这显示了您想要调用 exe 文件并使用 shell 命令将参数传递给它的场景。以下代码通过将 url 作为参数传递来检查 chrome.exe 所在的文件夹并从那里调用 www.google.com(假设您安装了 chrome):

Public Sub Display_Google()
  Dim chromePath As String
  chromePath = "C:\Program Files\Google\Chrome\Application\chrome.exe"

  If FileExists(chromePath) Then
  Shell (chromePath & " -url" & " " & "www.google.com"), vbMaximizedFocus
  Else

  chromePath = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
  Shell (chromePath & " -url" & " " & "www.google.com"), vbMaximizedFocus
  End If
End Sub

Public Function FileExists(ByVal FileName As String) As Boolean
    On Error Resume Next
    FileExists = Not CBool(GetAttr(FileName) And (vbDirectory Or vbVolume))
    On Error GoTo 0
End Function