PrintF – Transforming template strings

' This VB6 function returns a string with a set of parameters replaced with ' variables, similar to the C function printf().Public Function PrintF(strMask As String, ParamArray Values()) As String    On Error Resume Next    ' pass in a mask with variables in the order of , 1, 2, etc    ' if they are found, replace with the corresponding values()    Dim lngNbrValues As Long, lngCount As Long    Dim strX As String, strFind As String        lngNbrValues = UBound(Values)        ' first, find any \, 	 or 
 and replace those        strX = Replace(strMask, "\", "¥¥¥")    strX = Replace(strX, "	", vbTab)    strX = Replace(strX, "
", vbNewLine)        ' next, loop backward through the values, looking    ' for each item in turn.  If it's found, replace it    For lngCount = lngNbrValues To 0 Step -1        strFind = "{" + CStr(lngCount) + "}"        strX = Replace(strX, strFind, Values(lngCount))                strFind = "" + CStr(lngCount)        strX = Replace(strX, strFind, Values(lngCount))    Next lngCount    strX = Replace(strX, "¥¥¥", "")    PrintF = strX    On Error GoTo 0    End Function' And here's some code to test the function :Public Function GenerateNewFilename(strFilename As String) As String    Dim strNew As String    Dim dteNow As Date        dteNow = Now()    strNew = PrintF("_12_345_" + strFilename, Format(CStr(Year(dteNow)), _        "0000"), Format(CStr(Month(dteNow)), "00"), Format(CStr(Day(dteNow)), _        "00"), Format(CStr(Hour(dteNow)), "00"), Format(CStr(Minute(dteNow)), _        "00"), Format(CStr(Second(dteNow)), "00"))       GenerateNewFilename = strNewEnd Function' Note: in VB.NET, the String.Format provides much more than this,'  as it allows to specify how to format the values that replace the ' placeholders.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: