PDA

View Full Version : C# Style StringBuilder for VBA



DarkSprout
03-12-2008, 02:22 AM
I use a lot of VBA and C#, and I have to say: I Love The C# String Building Method, So.
I've written one for VBA - Please let me now what you think, and any improvements that could be included.
Use the included Test - to see what it can do (in the immediate window).

'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~
' Function: StrBld - C# Style StringBuilder for VBA
' DarkSprout [Feb08]
' ToUse: \\n (file://n/) For 2 NewLines, \n For a single Newline
' \uNNNN (NNNN) being a 4Digit hexadecimal value of a character number
' {index} as insertion points for the Items, starting at {0}
' TEST: ?StrBld("\u0022{0}X{1}\u004D\u0050\u004C{2}\u0022\nTest", "E", "A", "E")
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~
Public Function StrBld(StringToFormat As String, ParamArray Items()) As String
On Error GoTo StringBuildFail
Dim InputString As String, i As Integer, char As String
Const DBLINE = vbCrLf & vbCrLf
InputString = StringToFormat
'// Items
If Not IsMissing(Items) Then
For i = 0 To UBound(Items)
StringToFormat = Replace(StringToFormat, "{" & i & "}", Items(i))
Next i
End If

'// Unicode
Do While InStr(1, StringToFormat, "\u", vbBinaryCompare) > 0
i = InStr(1, StringToFormat, "\u", vbBinaryCompare)
char = Replace(Mid(StringToFormat, i, 6), "\u", "")
StringToFormat = Replace(StringToFormat, "\u" & char, Chr(Val("&H" & char)))
Loop

'// Newline(s)
StringToFormat = Replace(StringToFormat, "\\n (file://n/)", DBLINE)
StringToFormat = Replace(StringToFormat, "\n", vbNewLine)
StrBld = StringToFormat
Exit Function

StringBuildFail:
MsgBox Err.Description & ", With StrBld() " & DBLINE & "Please Check String = '" & InputString & "'", 64, "Error#" & Err.Number
Err.Clear
Resume Next
End Function


Realworld example:
In my error log recorder I use:

'Generate the SQL required to perform the database insert.
sql = StrBld("INSERT INTO tbl_CORE_ErrorLog (nErrorNumber, txtErrorMsg, txtUser, txtFormName, txtProcedureName) " _
& "SELECT {0}, '{1}', '{2}', '{3}', '{4}' ;", errNumber, errText, strUser, errForm, errProcedure)
DoCmd.RunSQL sql

And for MsgBoxs I use:
strMessage = StrBld("Please Validate Post Code, Does Not Match Known Format: [AANN NAA]\\nYou Entered:-\\n{0}\\n~~~\\n" _
& "One Usual Error Is Zeros for Ows (0/O).\nEXAMPLE: C015 insted of CO15", [txtPostCode])
MsgBox strMessage, 64, "Validate Post Code"
Or, you could just use it inline with the MsgBox
MsgBox StrBld("\u0022{0}X{1}\u004D\u0050\u004C{2}\u0022\nTest", "E", "A", "E"), 64

So... Please let me know if you like/could improve it.
=DarkSprout=