這是可以做到,但我會用託默勒格和別人同意這不是最好的方法。但是,這樣說,如果您將VBScript用作一種消除遺忘機制,VBScript可以偶爾創造奇蹟。它可以非常有效地用於模擬VBA中的多線程,從而可以分解有效負載並將其分發到單獨的VBScript以獨立運行。例如,您可以安排一組「單獨的VBScript」在後臺從網站進行批量下載,而VBA則繼續使用其他代碼。
下面是一些VBA代碼,我簡化了它來展示可以做什麼以及在運行時寫入一個簡單的VBScript。通常,我更喜歡使用'wshShell.Run """" & SFilename & """"
這意味着我可以忘掉它來運行它,但我已經包括在本例中此方法Set proc = wshShell.exec(strexec)
允許對象完成
測試中MODULE1
Option Explicit
Public path As String
Sub writeVBScript()
Dim s As String, SFilename As String
Dim intFileNum As Integer, wshShell As Object, proc As Object
Dim test1 As String
Dim test2 As String
test1 = "VBScriptMsg - Test1 is this variable"
test2 = "VBScriptMsg - Test2 is that variable"
'write VBScript (Writes to Excel Sheet1!A1 & Calls Function Module1.ReturnVBScript)
s = s & "Set objExcel = GetObject(, ""Excel.Application"") " & vbCrLf
s = s & "Set objWorkbook = objExcel.Workbooks(""" & ThisWorkbook.Name & """)" & vbCrLf
s = s & "Set oShell = CreateObject(""WScript.Shell"")" & vbCrLf
s = s & "Msgbox (""" & test1 & """)" & vbCrLf
s = s & "Msgbox (""" & test2 & """)" & vbCrLf
s = s & "Set oFSO = CreateObject(""Scripting.FileSystemObject"")" & vbCrLf
s = s & "oShell.CurrentDirectory = oFSO.GetParentFolderName(Wscript.ScriptFullName)" & vbCrLf
s = s & "objWorkbook.sheets(""Sheet1"").Range(""" & "A1" & """) = oShell.CurrentDirectory" & vbCrLf
s = s & "Set objWMI = objWorkbook.Application.Run(""Module1.ReturnVBScript"", """" & oShell.CurrentDirectory & """") " & vbCrLf
s = s & "msgbox(""VBScriptMsg - "" & oShell.CurrentDirectory)" & vbCrLf
Debug.Print s
' Write VBScript file to disk
SFilename = ActiveWorkbook.path & "\TestVBScript.vbs"
intFileNum = FreeFile
Open SFilename For Output As intFileNum
Print #intFileNum, s
Close intFileNum
DoEvents
' Run VBScript file
Set wshShell = CreateObject("Wscript.Shell")
Set proc = wshShell.exec("cscript " & SFilename & "") ' run VBScript
'could also send some variable
'Set proc = wsh.Exec("cscript VBScript.vbs var1 var2") 'run VBScript passing variables
'Wait for script to end
Do While proc.Status = 0
DoEvents
Loop
MsgBox ("This is in Excel: " & Sheet1.Range("A1"))
MsgBox ("This passed from VBScript: " & path)
'wshShell.Run """" & SFilename & """"
Kill ActiveWorkbook.path & "\TestVBScript.vbs"
End Sub
Public Function ReturnVBScript(strText As String)
path = strText
End Function
將這個這證明了變量可以傳遞的幾種方式。
難道你不能直接在VBA中運行代碼嗎? VBScript是VB的一個子集,可以在VB環境中幾乎未修改運行。 – Tomalak 2011-06-04 17:19:57
看到需求是我需要爲Excel宏中的變量賦值動態值(基本上是文件路徑和文件名)。我不想在每次更改路徑時都進入宏,因此如果我們可以通過VBS分配這些值,那麼它將很容易分配和更改值。 – 2011-06-04 17:23:27
這100%未能回答我評論中的問題。 – Tomalak 2011-06-04 17:25:22