将参数从vba传递给vbs

时间:2013-08-22 09:29:59

标签: vba vbscript

我有一个vb脚本和带有命令按钮的excel页面。

vb script --- test.vbs

MsgBox("Hello world")

excel vba代码

Private Sub CommandButton1_Click()
  Dim SFilename As String
    SFilename = "C:\Users\mkamaraj\Desktop\test.vbs" 'Change the file path

    ' Run VBScript file
    Set wshShell = CreateObject("Wscript.Shell")
    wshShell.Run """" & SFilename & """"
End Sub

当我单击Excel中的按钮时,它会执行VBScript并显示MessageBox。现在,我需要将TextBox Excel VBA传递到VBScript,该值应与VBScript MessagBox一起显示

我该怎么做?

3 个答案:

答案 0 :(得分:2)

您可以将参数发送到VBScript。请看下面的链接:

Can I pass an argument to a VBScript (vbs file launched with cscript)?

的VBScript:

MsgBox("Hello " & WScript.Arguments(0))

VBA:

Private Sub CommandButton1_Click()
  Dim SFilename As String
    SFilename = "C:\Users\mkamaraj\Desktop\test.vbs " & """Something Else""" 'Change the file path

    ' Run VBScript file
    Set wshShell = CreateObject("Wscript.Shell")
    wshShell.Run """" & SFilename & """"
End Sub

答案 1 :(得分:0)

一个简单的测试脚本来处理未命名的参数(showparms.vbs):

Option Explicit

Function qq(s)
  qq = """" & s & """"
End Function

Function Coll2Arr(oColl, nUB)
  ReDim aTmp(nUB)
  Dim i : i = 0
  Dim e
  For Each e In oColl
      aTmp(i) = e
      i       = i + 1
  Next
  Coll2Arr = aTmp
End Function

Dim oWAU  : Set oWAU = WScript.Arguments.Unnamed
Dim aWAU  : aWAU     = Coll2Arr(oWAU, oWAU.Count - 1)
Dim sArgs : sArgs    = "no arguments given"
If -1 < UBound(aWAU) Then
    sArgs = qq(Join(aWAU, """ """))
End If
MsgBox sArgs ' WScript.Echo sArgs

使用未命名参数(包含空格)调用.VBS的简单VBA子:

Option Explicit

Sub callVBS()
  Dim sFSpec As String: sFSpec = "p:\ath\to\showparms.vbs"
  Dim sParms As String: sParms = "one ""t w o"" three"
  Dim sCmd As String: sCmd = """" & sFSpec & """ " & sParms
  Dim oWSH: Set oWSH = CreateObject("WScript.Shell")
  oWSH.Run sCmd
End Sub

答案 2 :(得分:0)

我发现这很直接、简单且双引号更少。
需要记住在字符串命令中传递“your.vbs arg1 arg2”之间的空格
而且你不需要用双引号封装每个参数。

sCmd = "\\your\VBS\file\path\selectArgs.vbs"
arg1 = "ThisArg1"
arg2 = "ThisArg2"
sRun = sCmd & " " & arg1 & " " & arg2
Dim wsh As Object
Set wsh = CreateObject("Wscript.Shell")
wsh.Run "" & sRun & ""

'.Run will look like this:
'wsh.Run ""\\your\VBS\file\path\selectArgs.vbs ThisArg1 ThisArg2""