vba 如何将参数从 Excel 宏传递给批处理文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20371164/
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
How to Pass argument to batch file from Excel Macros?
提问by Samraan
From excel macros I'm trying to pass arguments to batch file. My approach is given below
从 excel 宏我试图将参数传递给批处理文件。我的方法如下
In Excel Macros:
在 Excel 宏中:
passArgument()
Dim var, path As String
Dim wsh As Object
var = "#"
Set wsh = VBA.CreateObject("WScript.Shell")
path = "C:\batchFile" + "\" + "run.bat"
Shell(path + " " + var, vbNormalFocus)
And I want to retrieve this var in batch file foe that I have followed like:
我想在我遵循的批处理文件敌人中检索这个 var:
set "n=%~1"
echo %n%
But it's displaying n itself instead of #. I am new to this kindly help me out, Thanks in advance
但它显示的是 n 而不是 #。我是新手,请帮助我,提前致谢
回答by MC ND
1 - You need a space between the batch file name and its parameters
1 - 批处理文件名及其参数之间需要一个空格
2 - If there is spaces inside the path to the batch file, full path and file name needs to be quoted
2 - 如果批处理文件的路径中有空格,则需要引用完整路径和文件名
3 - To execute a command using WScript.Shell
instance, you must call its Run
method. In your code wsh.Run( ....
. If you are using the Shell
method of VBA, then no need for WScript.Shell
.
3 - 要使用WScript.Shell
实例执行命令,您必须调用其Run
方法。在您的代码中wsh.Run( ....
。如果您使用的Shell
是 VBA的方法,则不需要WScript.Shell
.
4 - You are using strBatchName
that you have not declared nor initialized
4 - 您正在使用strBatchName
尚未声明或初始化的
5 - The sintax to retrieve the value of the first parameter in a batch file is %1
, with no closing percent sign
5 - 检索批处理文件中第一个参数的值的语法是%1
,没有结束百分号
6 - You are not setting the value of a variable called n
. There is a space after it. This should be written as set "n=%1"
or set "n=%~1"
to remove quotes in the first parameter if present. The included quotes in this line just prevent problems with added spaces in line or special characters inside argument.
6 - 您没有设置名为 的变量的值n
。后面有一个空格。这应该写为set "n=%1"
orset "n=%~1"
以删除第一个参数中的引号(如果存在)。此行中包含的引号只是防止在行中添加空格或参数中的特殊字符出现问题。
EDITED - Document the discussed configuration
编辑 - 记录讨论的配置
In excel
在excel中
Public Sub TestRun()
Shell quote("d:\test.cmd") + " " + quote("&<>,;!!"), vbNormalFocus
End Sub
Public Function quote(Text As String) As String
quote = Chr(34) + Text + Chr(34)
End Function
In batch file
在批处理文件中
@echo off
setlocal enableextensions disabledelayedexpansion
set "n=%~1"
setlocal enabledelayedexpansion
echo(!n!
endlocal
endlocal
pause