因為負責的項目的某項需求, 因此寫了一個陽春的WordWrap函式.
這函式依照使用者的需求 (一行多少個字) 然後自動將文字裁減, 可說是Mid() 的進階函式.
比如, 我有一組文字, "This is testing only", 我想要一行顯示17個字元, 然而17個字 = This is
testing o, 這很難看, 因此使用這函式將自動拿掉不合理的組合, 變成 "This is testing" -- line 1.
這函式是return Array 的方式, 因此如此使用的話...
Dim a as integer, i as integer
Dim b as Variant
b = WordWrap("This is testing only",17)
a = ubound(b)
For i=0 to a
Msgbox b(i)
Next i
顯示結果:
This is testing
only
這函式還不夠完善, 因為return 出來的Array數是所要顯示的一行的字數. 懶得修改, 因此只把雛型放出來.
這函式依照使用者的需求 (一行多少個字) 然後自動將文字裁減, 可說是Mid() 的進階函式.
比如, 我有一組文字, "This is testing only", 我想要一行顯示17個字元, 然而17個字 = This is
testing o, 這很難看, 因此使用這函式將自動拿掉不合理的組合, 變成 "This is testing" -- line 1.
這函式是return Array 的方式, 因此如此使用的話...
Dim a as integer, i as integer
Dim b as Variant
b = WordWrap("This is testing only",17)
a = ubound(b)
For i=0 to a
Msgbox b(i)
Next i
顯示結果:
This is testing
only
這函式還不夠完善, 因為return 出來的Array數是所要顯示的一行的字數. 懶得修改, 因此只把雛型放出來.
Function WordWrap(Text As String, WordsLimit As Integer, Optional WrapBy As String)
'Create by Gordon Lim (gordon@perridot.com) 2008-07-04
'Text = Input String
'WordsLimit = How many characters want to display per line
'WrapBy = Auto wrap by what string
Dim length As Integer, i As Integer, x As Integer, roundLoop As Integer, stopAtLoop As Integer
Dim newWrapBy As String
Dim s_str As Variant, newArrStr As Variant
If (WrapBy = "") Then
WrapBy = " "
End If
length = Len(Text)
s_str = Split(Text, WrapBy)
newWrapBy = WrapBy
If (length > WordsLimit) Then
ReDim newArrStr(UBound(s_str))
stopAtLoop = 0
'For x = 1 To roundLoop
For x = 1 To WordsLimit
For i = stopAtLoop To UBound(s_str)
If i = UBound(s_str) Then
newWrapBy = ""
Else
newWrapBy = WrapBy
End If
If (Len(newArrStr(x - 1) & s_str(i) & WrapBy) <= WordsLimit) Then
newArrStr(x - 1) = newArrStr(x - 1) & s_str(i) & WrapBy
Else
Exit For
End If
Next i
If (i = x) Then
Exit For
Else
stopAtLoop = i
End If
Next x
Else
ReDim newArrStr(1)
For i = 0 To UBound(s_str)
If i = UBound(s_str) Then
newWrapBy = ""
Else
newWrapBy = WrapBy
End If
If (Len(newArrStr(0) & s_str(i) & WrapBy) <= WordsLimit) Then
newArrStr(0) = newArrStr(0) & s_str(i) & WrapBy
End If
Next i
End If
WordWrap = newArrStr
End Function
留言
張貼留言