2013-08-22 155 views
2

我有一個vb腳本和帶有命令按鈕的excel頁面。將參數從vba傳遞給vbs

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。現在,我需要將TextBoxExcel VBAVBScript並且該值應該與VBScriptMessagBox一起顯示。

我該怎麼做?

+1

mehow,感謝您的有用編輯 – Pinky

回答

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 
+0

嗨,馬克懷爾迪,我想你的代碼。它顯示錯誤,如「對象IWshShell3的方法運行失敗」。 – Pinky

+0

我編輯了我原來的回覆,在其他東西之間加入了雙引號。再試一次:) – Mark

+0

馬克,應該用Run方法添加參數。我嘗試了代碼,如wshShell.Run「」「」&SFilename&「」「」&「SomethingElse」。現在它顯示MessageBox和Hello SomethingElse。感謝幫助。 – Pinky

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 

一個簡單的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