[VB6] 模擬 VBNET 的 String.Format

話說,上周五須要去改寫一個舊的 VB6 專案,太久沒寫 VB6 了,已經麻痺不仁了… 覺得 VB6 沒有 VB.NET 的 String.Format ,簡直是一種罪惡…
好吧,我承認,是我寫習慣 VBNET 了,回頭用 VB6 已經不習慣了,所以只好在 VB6 寫個小函數提供類似的功能:

程式碼

選單 專案 設定引用項目 Microsoft VBScript Regular Expressions 5.5

仿 VBNET 的 String.Format

Public Function StringFormat(ByVal strFormat As String, ParamArray varArray() As Variant) As String

     ‘ strFormat = “{1:yyyy/MM/dd HH:mm:ss}"

     ‘ $1 = objMatch.SubMatches(0) = 1

     ‘ $2 = objMatch.SubMatches(1) = :yyyy/MM/dd HH:mm:ss

     ‘ $3 = objMatch.SubMatches(2) = yyyy/MM/dd HH:mm:ss

     Dim objRegExp As New RegExp

     Dim objMatch As Match

     Dim colMatches As MatchCollection

 

     RetStr = strFormat

     strPattern = “\{(\d+)(:([^}]+))?}" ‘{Index[:Format]}

 

     On Error Resume Next

     With objRegExp

          .Pattern = strPattern

          .IgnoreCase = True

          .Global = True

 

          If .Test(strFormat) Then

               Set colMatches = objRegExp.Execute(strFormat)

               For Each objMatch In colMatches

                    strFormat = Replace(strFormat, objMatch.Value, Format(varArray(objMatch.SubMatches(0)), objMatch.SubMatches(2)))

               Next

          End If

     End With

     On Error GoTo 0

 

     StringFormat = strFormat

End Function

 

Categories: 技術分享 | 8 則迴響

文章導覽

8 thoughts on “[VB6] 模擬 VBNET 的 String.Format

  1. WAYNE

    ByVal ParamArray varArray() As Object 提示不能這樣寫 , 編譯不會過

    喜歡

  2. WAYNE

    我用

    Private Sub Form_Load()

    Dim SS As String
    SS = “hi!{1}"

    MsgBox StringFormat(SS, “user1″)
    End Sub

    顯示出來並沒有被處理, 而是在.TEST(strFormat)時就顯示為FALSE跳掉了, 可以麻煩你DEMO一下嗎?

    喜歡

    • 一個呼叫案例:

      Public Function AddEventLog(ByVal CallFunName As String, ByVal ErrorMessage As String, Optional ByVal ErrNumber As Long = -1) As String
      Dim strMessage As String
      strMessage = StringFormat(“[{0:yyyy/MM/dd HH:mm:ss}] {1}: [{3}]{2}", Now, CallFunName, ErrorMessage, ErrNumber)
      SaveLog strMessage
      AddEventLog = strMessage
      End Function

      喜歡

      • 我發現
        strPattern = “\{(\d+)(:([^}]+))?}" ‘{Index[:Format]}
        這句的倒斜線在 Live Space 搬到 wordpress 時,被系統吃掉,可能是你用起來有問題的原因。

        喜歡

  3. wayne

    感謝萬分!!

    喜歡

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 變更 )

Twitter picture

You are commenting using your Twitter account. Log Out / 變更 )

Facebook照片

You are commenting using your Facebook account. Log Out / 變更 )

Google+ photo

You are commenting using your Google+ account. Log Out / 變更 )

連結到 %s

在 WordPress.com 建立免費網站或網誌.

%d 位部落客按了讚: