VBA基础
非常好用的Format函数
2009-07-27 08:58:54
Function ArrayFormat(expression As String, ParamArray formatException()) As String

Public Function ArrayFormat(expression As String, ParamArray formatException()) As String

   Dim strFind As String, strReplace As String, strTemp As StringOffice

   Dim i As Integer

   strTemp = expression   For i = 0 To UBound(formatException) )j$vE,u&w0E+W‑l0        strFind = "{" & i & "}": strReplace = formatException(i)Office中国社区门户#H)aCocP-X        strTemp = Replace(strTemp, strFind, strReplace)

   Next

   ArrayFormat = strTempOffice End Function 代码很短吧,只有10行。但它会带给我们一份不一样的感受。

我们先来个测试:

Sub Test()Dim str As String

    str = "他们分别来自:{0}{1}{2}{3}{4}{5}"     Debug.Print ArrayFormat(str, "北京", "上海", "广州", "山东", "福建", "海南")­End Sub

执行上面的代码可在立即窗体中看到:他们分别来自:北京、上海、广州、山东、福建、海南。这相对于用 & 来串接字符串是否要方便些呢?

使用这个函数有以下注意事项:

格式项的语法是{index}index 为从零开始的整数,指示对象列表中要格式化的元素。如果由 index

指定的对象是 空,则格式项将忽略。­2expression必须使用前导大括号字符和后缀大括号字符,即{}。若要在expression中指定单个大括号字符,请指定两个前导大括号字符或后缀大括号字符(即{{}})。

3、当可选参数formatSting的的最大下标(即:UBound(formatException))与格式项中index 的数值不相符时,不相符的部分都将被忽略。

 

例如:

Sub Test1()Dim str As String     str = "他们分别来自:{0}{1}{2}{3}"

    Debug.Print  ArrayFormat(str, "北京", "上海", "广州", "山东", "福建", "海南")End Sub

返回:他们分别来自:北京、上海、广州、山东

Sub Test2()Dim str As String     str = "他们分别来自:{0}{1}{2}{3}{4}{5}"Office中国社区门户!P*W hGq    Debug.Print ArrayFormat(str, "北京", "上海", "广州")Office中国社区门户5{sk i j9i‑W3hEnd Sub

返回:他们分别来自:北京、上海、{2}{3}{4}{5}