Are you leading me on?

Recently in the VBScript forum at ScriptingAnswers.com there was a question about creating a file name from the current date, but with leading zeros. This is a pretty common question. It is easy enough to get the month or day portion of the current day.

dy=Day(Now)

However there is no VBScript function to format this to provide a leading 0. Neither FormatDate or FormatNumber can help. So instead I offered a function. Here is a modified version of what I originally offered that is a little more flexible.

'///////////////////////////////////////////
' Pad text with a leading character
'//////////////////////////////////////////
Function PadText(strText,iLen,strChar)
 
If Len(strText) >= iLen Then 
    strText=strText
Else 
    Do Until Len(strText)=iLen
        strText=strChar & strText
    Loop
End If
 
PadText=strText
 
End Function

This function takes a string, a length, and a character to pad to the front to make it equal to the requested length. In this situation we want to use a 0 to make the string 2 characters long. Here’s how I can incorporate this function.

mo=PadText(Month(Now),2,0)
dy=PadText(Day(Now),2,0)
yr=Year(Now)
   
sFileName = "C:\Report_" & mo & "-" & dy & "-" & yr & ".txt" 
 
WScript.Echo sFileName
'returns C:\Report_02-06-2009.txt

The Month and Day portion of the current date are processed by the function which uses a 0 to make them 2 characters long. If the string is already long enough, then the function returns the original string. But we’re not limited to something like leading 0s. Look at this.

myArray=Array("Jeff","Alex","Scott","David","Stephen")
For Each sName In myArray
  WScript.Echo PadText(sName,10,".")
Next

Each string in the array will be padded so that the total string length is 10 characters. The string will be padded with a period which produces output like this:

……Jeff
……Alex
…..Scott
…..David
…Stephen

This might be useful in formatting information in a report. You could even skip the period and use a space.

WScript.Echo PadText(sName,10,” “)

This function pads to the right, but it wouldn’t be to difficult to create a function that pads to the left. Even better, modify this function so that you can specify left or right padding! But I’ll leave that for you to try out.

Download a text version of this function here.

If you need help with VBScript, please use the forums at ScriptingAnswers.com and don’t forget about my complete VBScript reference book WSH and VBScript Core: TFM.