1,065
社区成员
发帖
与我相关
我的任务
分享
'-----------------------------------------------------------------------------------
' 函数名称: wsprintf()
' 函数功能: 仿C++中sprintf()函数格式化输出数据
'
' 参数说明:
' [In] strFMT : String '输出内容和输出格式化因子的字符串
' [In] vArgs() : Variant '输出的参数列表
'
' 返回类型: 字符型, 返回格式化后的字符串
'
' 格式化因子:
' %s ---- 字符串
' %d ---- 日期型
' %i ---- 数字型
' %x ---- 十六进制数字
'-----------------------------------------------------------------------------------
Public Function wsprintf(ByVal strFMT As String, ParamArray vArgs() As Variant) As String
Dim strArr() As String
Dim strRight As String
Dim strOut As String
Dim i As Long, j As Long
Dim lCount As Long
Dim Args() As Variant
strArr = Split(strFMT, "%")
On Error Resume Next
Args = IIf(IsArray(vArgs(0)), vArgs(0), vArgs)
lCount = UBound(strArr)
For i = 1 To lCount
If Right$(strArr(i - 1), 1) = "\" Then
strArr(i - 1) = Left$(strArr(i - 1), Len(strArr(i - 1)) - 1)
strArr(i) = "%" & strArr(i)
ElseIf strArr(i) <> vbNullString Then
strRight = Right$(strArr(i), Len(strArr(i)) - 1)
Select Case LCase$(Left$(strArr(i), 1))
Case "x"
strArr(i) = "&H" & Hex$(Args(j)) & strRight
Case "d"
strArr(i) = Format(Args(j), "yyyy-MM-dd hh:mm:ss") & strRight
Case Else
strArr(i) = Args(j) & strRight
End Select
j = j + 1
End If
Next
strOut = Join(strArr, "")
strOut = Replace(strOut, "\n", vbCrLf)
wsprintf = strOut
End Function
Function fmt(str, args)
' works like the printf-function in C.
' takes a string with format characters and an array
' to expand.
'
' the format characters are always "%x", independ of the
' type.
'
' usage example:
' dim str
' str = fmt( "hello, Mr. %x, today's date is %x.", Array("Miller",Date) )
' response.Write str
Dim res ' the result string.
res = ""
Dim pos ' the current position in the args array.
pos = 0
Dim i
For i = 1 To Len(str)
' found a fmt char.
If Mid(str, i, 1) = "%" Then
If i < Len(str) Then
' normal percent.
If Mid(str, i + 1, 1) = "%" Then
res = res & "%"
i = i + 1
' expand from array.
ElseIf Mid(str, i + 1, 1) = "x" Then
res = res & CStr(args(pos))
pos = pos + 1
i = i + 1
End If
End If
' found a normal char.
Else
res = res & Mid(str, i, 1)
End If
Next
fmt = res
End Function