gpt4 book ai didi

vba - WScript.Shell 运行一个脚本,路径中有空格,参数来自 VBA

转载 作者:行者123 更新时间:2023-12-04 14:10:25 28 4
gpt4 key购买 nike

我需要使用 WScript.Shell 从 VBA 调用脚本 (R)。文件路径包含空格。此外,一系列参数被传递给脚本,其中几个还包含空格。

我已经在路径、参数甚至整个字符串(特别是 this here)周围尝试了所有可以想到的引号和双引号组合。当需要传递参数时,似乎没有任何效果(我在命令行中得到“C:\Program”未被识别”或“无效语法”错误)。

Option Explicit
Private Const QUOTE As String = """"

Sub test()
Dim WS_Shell As Object
Set WS_Shell = VBA.CreateObject("WScript.Shell")
Dim err_code As Long

Dim path As String
Dim arg_1 As String
Dim arg_2_with_spaces As String

Dim complete_cmd_str As String

path = "C:\Program Files\R\R-3.3.2\bin\Rscript.exe"
arg_1 = "F:\path\to\my\script.R"
arg_2_with_spaces = "A string-arg with spaces"

complete_cmd_str = "cmd.exe /K " & QUOTE & path & QUOTE & " " _
& QUOTE & arg_1 & QUOTE & " " _
& QUOTE & arg_2_with_spaces & QUOTE

Debug.Print complete_cmd_str
err_code = WS_Shell.Run(complete_cmd_str, vbMinimizedNoFocus, True)
End Sub

所有这一切都发生在 Windows 7 上。

如何在路径和要传递的参数中运行带空格的命令行脚本?非常感谢任何帮助!

更新:

如果从命令字符串中删除前缀“cmd.exe/K”,则代码有效。但是,为了测试和调试,我想在脚本运行后让 shell 窗口保持打开状态。如何实现?

最佳答案

enter image description here我曾经运行脚本并从 Excel 传递参数,这段代码对我有用。

为了运行脚本非常重要,首先指定 Rscript.exe 的路径和 R 脚本(.r 文件)的路径,然后您可以使用空格传递参数。

Sub run_R()

Dim shell As Object
Set shell = VBA.CreateObject("WScript.Shell")
Dim waitTillComplete As Boolean: waitTillComplete = True
Dim style As Integer: style = 1
Dim errorcode As Integer
Dim path As String

path = Chr(34) & "C:\R\R-3.4.0\bin\i386\Rscript.exe" & Chr(34) & " " & Chr(34) & "C:\Users\userexample\Desktop\accionable.r" & Chr(34) & " " & Chr(34) & "Argument 1" & Chr(34)

errorcode = shell.Run(path, style, waitTillComplete)

End Sub

读取参数的R代码:

args = commandArgs(trailingOnly = T)
cat(args[1])

关于vba - WScript.Shell 运行一个脚本,路径中有空格,参数来自 VBA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49652606/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com