2015年10月2日 星期五

【Excel VBA】文字操作。string manipulation, parsing

Join Strings
We use the & operator to concatenate (join) strings.Code:
Dim text1 As String, text2 As String
text1 = "Hi"
text2 = "Tim"
MsgBox text1 & " " & text2
=> Hi Tim

Left
To extract the leftmost characters from a string, use Left.
Code:
Dim text As String
text = "example text"
MsgBox Left(text, 4)
=>exam


Right
To extract the rightmost characters from a string, use Right.
We can also directly insert text in a function.Code:
MsgBox Right("example text", 2)
=>xt


Mid
To extract a substring, starting in the middle of a string, use
 ' Creates text string.
Dim TestString As String = "Mid Function Demo"

' Returns "Mid".
Dim FirstWord As String = Mid(TestString, 1, 3)

' Returns "Demo".
Dim LastWord As String = Mid(TestString, 14, 4)

' Returns "Function Demo".
Dim MidWords As String = Mid(TestString, 5)
(第三欄不填,可以抓到結尾)


Len(含空白)
To get the length of a string, use Len.
Code:
MsgBox Len("example text")
=>12


Instr
To find the position of a substring in a string, use Instr.
Code:
MsgBox Instr("example text", "am")
=> 3



Compare two strings.
StrComp


Convert strings.
StrConv


Reverse a string.
InStrRev, StrReverse


Convert to lowercase or uppercase.
Format, LCase, UCase


Create a string of repeating characters.
Space, StrDup


Find the length of a string.
Len


Format a string.
Format, FormatCurrency, FormatDateTime, FormatNumber, FormatPercent






沒有留言:

張貼留言