VBScript create function alias for WScript.Echo

2019-09-15 18:11发布

问题:

I know that it has not any sense. But Nevertheless.

I want to create full copy of WScript.Echo

My approach is to create function with another short name.

Sub print(arguments)
    WScript.Echo arguments
End Sub

In WScript.Echo arguments are array of strings WScript.Echo Arg1, Arg2, Arg3... Optional string values to be displayed. (may be not array, but it looks like list of strings)

My question is how I can pass same argument to my function? Or may be it is not possible in general.

回答1:

WScript.Echo is a variadic Sub (taking an arbitrary number of arguments). You can't write such Functions/Subs/Method in VBScript. In VBA you can use a Parameter Array or the Optional keyword.

For VBScript: You could write a Sub that takes an array a as its only parameter and WScript.Echo Join(a), but I doubt that

print Array(...)

is worth (1** less letter to type) the effort.

Update: ** Obviously I can't count.



回答2:

Below is VBS code that provides the same functionality as ParamArray modifier in VBA: it allows to pass arbitrary number of arguments, and called function receives passed arguments as array. It uses ScriptControl JScript arguments property to prepare the array of arguments.

Dim oSC, Echo

Set oSC = CreateObject("MSScriptControl.ScriptControl")
oSC.Language = "JavaScript"
oSC.AddCode "echo = function () {var dict = new ActiveXObject('Scripting.Dictionary'); for(var i=0; i<arguments.length; i++) {dict.add(i, arguments[i]);} echoArr(dict.Items());}"
oSC.AddObject "echoArr", GetRef("EchoArr"), True
Set Echo = oSC.Eval("echo")

Echo "one", "two", "three"
Echo "True variadic sub"

Function EchoArr(arr)
    WScript.Echo Join(arr)
End Function

To call WScript.Echo in variadic method manner you can use Execute, and replace EchoArr function in code above with following code (but I am not sure it has practical value):

Function EchoArr(arr)
    Dim s, i
    s = "WScript.Echo "
    i = 0
    For i = 0 to UBound(arr)
        s = s & "arr(" & i & ")"
        If i < UBound(arr) Then s = s & ", "
    Next
    Execute s
End Function