从Excel VBAmacros执行VBScript文件

我需要一些excel vba示例,在VBA代码(Excelmacros)中,我可以调用VBScript,并从vbscript中获取一些文件名和目录信息等值,并将其分配给VBA代码中的variables。 先谢谢你

有些事情是这样的

VBAmacros:

Sub Foo2Script Dim x As Long x=2 'Call VBscript here MsgBox scriptresult End Sub 

VBScript中:

 Dim x, y ,Z x = x_from_macro y = x + 2 Z = X+Y scriptresult = y,Z 

这是可以做到的,但我必须同意Tomalak和其他人的意见,这不是最好的方法。 但是,这样说,VBScript可以偶尔使用它作为一种消除遗忘机制。 它可以很有效地用于模拟VBA中的multithreading,从而将有效负载进行分解,并将其划分为单独的VBScript以独立运行。 例如,你可以安排一个单独的VBScripts“群”在后台从网站大量下载,而VBA继续与其他代码。

下面是一些VBA代码,我已经简化了,以显示可以做什么,并在飞行中写一个简单的VBScript。 通常我更喜欢使用'wshShell.Run """" & SFilename & """"来运行它,这意味着我可以忘掉它,但是我已经在这个例子中包含了这个方法Set proc = wshShell.exec(strexec)完成对象的testing

把它放在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 

这certificate了variables可以传递的几种方法。