0

I would like to use C-style string formatting in VBA to make it easier to send SQL instructions the same way I do in Python.

Is there anything similar?

sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)

Thank you,

Marcelo Gazzola
  • 907
  • 12
  • 28

2 Answers2

1

You can use a System.Text.StringBuilder like this:

Function FormatString(Text As String, ParamArray Args() As Variant) As String
    Dim values()
    Dim n As Long
    ReDim values(UBound(Args))

    For n = 0 To UBound(Args)
        values(n) = Args(n)
    Next

    With CreateObject("System.Text.StringBuilder")
        .AppendFormat_4 Text, values
        FormatString = .toString
    End With
End Function

Test

Immediate Window Screenshot You can find a class that I wrote to wrap the System.Text.StringBuilder here: Bringing The System.Text.StringBuilder Up To Lightning Speed In The VBA.

TinMan
  • 6,624
  • 2
  • 10
  • 20
0

I found this, it helped me, is a similar way:

Is there an equivalent of printf or String.Format in Excel

Public Function printf(mask As String, ParamArray tokens()) as String

    Dim i as Long
    For i = 0 To Ubound(tokens)
        mask = replace$(mask, "{" & i & "}", tokens(i))
    Next

    printf = mask

End Function
myString = printf("Some text '{0}', more text: '{1}'", A1, A2)
Marcelo Gazzola
  • 907
  • 12
  • 28