Execute & ExecuteGlobal比较
Execute和ExecuteGlobal都是指执行一段或多段声明(Statement),我的理解就是去引用其他模块定义的变量或者函数。这里的Statement可以用字符串来标识,可以是单句,也可以是多句,甚至是一整个vbs文件。
两者的区别主要在于作用域上:
Execute:声明中变量的作用域和执行Execute语句处的作用域相同
ExecuteGlobal:声明中变量的作用域始终是全局(Global)
这里引用msdn上的一个例子来说明
Dim X ' Declare X in global scope.
X = "Global" ' Assign global X a value.
Sub Proc1 ' Declare procedure.
Dim X ' Declare X in local scope.
X = "Local" ' Assign local X a value.
' The Execute statement here creates a
' procedure that, when invoked, prints X.
' It print the global X because Proc2
' inherits everything in global scope.
Execute "Sub Proc2: Print X: End Sub" '-1-
Print Eval("X") ' Print local X.
Proc2 ' Invoke Proc2 in Proc1's scope. '-2-
End Sub
Proc2 ' This line causes an error since '-3-
' Proc2 is unavailable outside Proc1.
Proc1 ' Invoke Proc1.
Execute "Sub Proc2: Print X: End Sub" '-4-
Proc2 ' This invocation succeeds because Proc2 '-5-
' is now available globally.
可以看到,在位置-1-虽然有在Execute中声明Proc2,但Proc2的作用域和Execute所在位置的作用域是一样的,即只在Proc1中有效。因此在位置-2-可以调用,但是在位置-3-就不能调用。同理,在位置-4-执行Execute语句时,由于本身该处的作用域就是Global,所以位置-5-处执行Proc2也是ok的。
这里如果要修正位置-3-的报错,只需要将位置-1-处的声明改成ExecuteGlobal就可以了。
能否重复引用同一段内容?
应用:如何在一个vbs中引用另一个vbs的函数和全局变量?
可以通过ExecuteGloabl函数将其他vbs中的函数引用到当前的模块中。为了方便起见可以定义一个Include
Sub Include(sInstFile)
Dim oFSO, f, s
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set f = oFSO.OpenTextFile(sInstFile)
s = f.ReadAll
f.Close
ExecuteGlobal s
End Sub