【问题标题】:passing argument from vba to vbs将参数从 vba 传递到 vbs
【发布时间】:2013-08-24 22:56:47
【问题描述】:

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

vb脚本---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 一起显示。

我该怎么做?

【问题讨论】:

  • mehow,感谢您的有用编辑

标签: vba vbscript


【解决方案1】:

您可以将参数发送到 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

【讨论】:

  • 嗨 Mark Wylde,我试过你的代码。它显示错误,如“对象 IWshShell3 的方法运行失败”。
  • 我已经编辑了我的原始回复,在其他东西之间包含双引号。再试一次:)
  • 标记,参数要加上Run方法。我尝试了类似 wshShell.Run """" & SFilename & """" & "SomethingElse" 的代码。现在它显示带有 Hello SomethingElse 的 MessageBox。感谢您的帮助。
【解决方案2】:

处理未命名参数的简单测试脚本 (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

一个简单的 VBA 子程序,用于调用带有未命名参数(包含空格)的 .VBS:

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

【讨论】:

    【解决方案3】:

    我发现这是直截了当的,简单的,更少的双引号。
    需要记住在字符串命令中传递“your.vbs arg1 arg2”之间的空格
    而且您不需要将每个 arg 都用双引号封装起来。

    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""
    

    【讨论】:

      猜你喜欢
      • 2012-12-02
      • 2018-01-20
      • 1970-01-01
      • 1970-01-01
      • 2012-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多