S..*_*S.. 3 vbscript excel vba excel-vba
我需要一些excel vba示例,在VBA代码(Excel宏)中,我可以调用VBScript,并从vbscript获取文件名和目录信息等值,并将其分配给VBA代码中的变量.先感谢您
有点像这样
VBA宏:
Sub Foo2Script
Dim x As Long
x=2
'Call VBscript here
MsgBox scriptresult
End Sub
Run Code Online (Sandbox Code Playgroud)
VBScript中:
Dim x, y ,Z
x = x_from_macro
y = x + 2
Z = X+Y
scriptresult = y,Z
Run Code Online (Sandbox Code Playgroud)
可以这样做,但我不得不同意Tomalak和其他人认为这不是最好的方法.但是,如果你把它用作一种火灾和遗忘机制,那么VBScript偶尔可以创造奇迹.它可以非常有效地用于模拟VBA中的多线程,从而分解有效负载并将其分配给各个VBScripts以独立运行.例如,你可以安排一个单独的VBScripts"群"在后台从网站大量下载,而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
Run Code Online (Sandbox Code Playgroud)
这证明了变量可以传递的几种方式.