I want to create a FormatString function for VBScript that works the same as String.Format in .Net.
I found i can use the System.Text.StringBuilder object in VBScript and tested the following code which works
Option Explicit
Dim sbText 'As System.Text.StringBuilder
Set sbText = CreateObject("System.Text.StringBuilder")
Call sbText.AppendFormat_5( _
Nothing, _
"My name is {0} and the current date time is '{1:dd MMMM yyyy HH:mm:ss}'", _
Array("Robert", Now))
Call MsgBox(sbText.ToString())
I then went to put it in a function and it fails see below
Option Explicit
Function FormatString(ByVal sText, ByVal Arguments) 'As String
Dim sbText 'As System.Text.StringBuilder
'Test the input variables
If Not TypeName(sText) = "String" Then _
Err.Raise 5 'vbErrInvalidProcCallOrArg
If Not IsArray(Arguments) Then _
Err.Raise 5 'vbErrInvalidProcCallOrArg
Set sbText = CreateObject("System.Text.StringBuilder")
Call sbText.AppendFormat_5(Nothing, sText, Arguments)
FormatString = sbText.ToString()
End Function
Call MsgBox(FormatString( _
"My name is {0} and the current date time is '{1:dd MMMM yyyy HH:mm:ss}'", _
Array("Robert", Now)))
It fails on Call sbText.AppendFormat_5(Nothing, sText, Arguments)
with the error "Invalid procedure call or argument: 'sbText.AppendFormat_5'".
So what i don't understand is why outside a function i can pass the following types in order:
Nothing
String
Arrary
and they work but inside a function it doesn't.
Can anybody assist?
You need to pass the array parameter by value:
Call sbText.AppendFormat_5(Nothing, sText, Arguments)
==>
Call sbText.AppendFormat_5(Nothing, sText, (Arguments))