Tuesday, December 30, 2008

Script Code: String Padding

I think I might start digging through my pile of scripts and posting useful pieces in case it helps anyone.  Pardon the annoyance if some of these are too "common" or seen elsewhere.  Scripts often spring from the inspiration of others, not intending to plaguerize or anything like that.  This piece of code takes a string and pads a string to the left or right end until it reaches a desired length.  This is often useful for making 2-digit date values like "09" or "01". 

    Function PadString (strBase, iLen, sChar, sSide)
        Dim retval
        retval = Trim(strBase)
        Do While Len(retval) <>
            If Ucase(Left(sSide, 1)) = "L" Then
                retval = sChar & retval
            Else
                retval = retval & sChar
            End If
        Loop
        PadString = retval
    End Function

An example for which this might come in handy would be concatenating a date string value with a fixed-length.  A typical format would be "YYYY-MM-DD".  So if you wanted to make a folder or filename with the date format appended or included you could use the PadString() function to ensure the MM and DD were always 2-characters in length.

    Const DateTemp = "YYYY-MM-DD"

    DateString = Replace(DateTemp, "YYYY", Year(Now))
    DateString = Replace(DateString, "MM", PadString(Month(Now), 2, "0", "LEFT"))
    DateString = Replace(DateString, "DD", PadString(Day(Now), 2, "0", "LEFT"))

So if the current date was December 30, 2008, the above chunk of code would produce "2008-12-30".  Using a string-replace technique allows you to shuffle the format around without having to modify any of the code below it.  So you could change DateTemp to "MM_DD_YYYY" if you wanted and it would produce "12_30_2008" as well.

This is a rather basic example, so you will probably find ways to improve or expand upon this to suit your needs.
Post a Comment