As someone who comes from a VB background I sometimes get frustrated with some of the design decisions taken with VBScript. Why, for example, did MS decide not include the rather useful Format function and instead include the less powerful and less flexible Formatxxxxx functions?
And, looking at some of the sometimes convoluted methods other people in this forum have adopted to get a date or number just how they want it, it looks like I'm not the only one.
Whilst I was investigating leveraging some of .Net's various collection classes for use in VB (and VBScript) it suddenly occurred to me that we also have access to .Net's System.Text.StringBuilder ... which means we can write ourselves a fairly succint Format function that works much like VBs and includes a bunch of additional functionality:
and some examples of using it:
For some of the addtional formatting features you'll need to look at the .Net formatting documentation on MSDN. This is probably as good a place as any to start
Hope some of you find this useful.
And, looking at some of the sometimes convoluted methods other people in this forum have adopted to get a date or number just how they want it, it looks like I'm not the only one.
Whilst I was investigating leveraging some of .Net's various collection classes for use in VB (and VBScript) it suddenly occurred to me that we also have access to .Net's System.Text.StringBuilder ... which means we can write ourselves a fairly succint Format function that works much like VBs and includes a bunch of additional functionality:
Code:
[blue]Public Function vbsFormat(Expression, Format)
vbsFormat = CoreFormat("{0:" & Format & "}", Expression)
End Function
' Allows more of the .NET formatting functionality to be used directly if required
Public Function CoreFormat(Format, Expression)
CoreFormat = Expression
On Error Resume Next
With CreateObject("System.Text.StringBuilder")
.AppendFormat Format, Expression
If Err=0 Then CoreFormat = .toString
End With
End Function[/blue]
Code:
[blue]MsgBox vbsFormat(Now(), "dd-MMM-yyyy") ' basic example
MsgBox vbsFormat(Now(), "MM_dd_yyyy_HHmm") ' as per the format wanted in thread329-1566954
MsgBox vbsFormat(12.5, "Numeric example: 0.00") ' basic numeric
Msgbox vbsFormat(02075551234,"(0###)###-####")
' demonstrate a few more advanced numerical custom format
MsgBox vbsFormat(6, "+00.00;(0.00);Eek - it's Nil!")
MsgBox vbsFormat(-6, "+00.00;(0.00);Eek - it's Nil!")
MsgBox vbsFormat(0, "+00.00;(0.00);Eek - it's Nil!")
' Now demonstrate fractionally more advanced formatting capability provided by .NET
MsgBox CoreFormat("Various formats all in the same line: {0:##0.0} or {0:£##0.00} and even {0:00.00%}", 1.25)[/blue]
Hope some of you find this useful.