我有一个VBA宏,我需要在其中获取splitStr(1)= str2,str3; splitStr(2)= str4; ....
string1 = "str1,""str2,str3"",str4,str5,str6"
splitStr = Split(string1,",")
Debug.Print splitStr(1)
"str2
谢谢
答案 0 :(得分:0)
Split(expression [,delimiter] [,limit] [,compare] )
函数正在逐个字符地搜索字符串,以查找分隔符,或者根据分隔符逐个子字符串地查找子字符串。您有几种选择:
使用Split(string1,",")
并按以下方式在splitStr中获得结果数组:
splitStr(0) = str1
splitStr(1) = "str2
splitStr(2) = str3"
splitStr(3) = str4
splitStr(4) = str5
splitStr(5) = str6
然后使用以下代码以所需方式“修复”结果
splitStr(1) = Replace(splitStr(1), """", "") & Replace(splitStr(2), """", "")
'splitStr(1) now contains str2str3
'splitStr(2) still contains str3"
答案 1 :(得分:0)
分割的字符串将标记保持在引号内
尝试使用临时转换为►Byte
类型的方法,该方法可以更快地遍历字符串。
方法
基本上所有在引号内的逗号暂时转换为另一个字符(例如,分号),以便您可以像往常一样通过将最终的分号替换回普通逗号来进行拆分。
请参见以下代码示例的进一步说明:
Sub testByte()
Const COMMA& = 44, QUOT& = 34, SEMI& = 59 ' constants for comma, quot.mark, semicolon
Dim b() As Byte, i As Long, bQU As Boolean
Dim string1$, sTemp$
' [0] string to be splitted
string1 = "str1,""str2,str3"",str4,str5,str6"
' [1] temporary conversion of commatas in quotations to another character using the BYTE type
b = string1 ' Assign string to bytes
For i = 0 To UBound(b) Step 2 ' check each bytes representation of character
If b(i) = QUOT Then bQU = IIf(bQU, False, True) ' check quotation starts
If bQU Then If b(i) = COMMA Then b(i) = SEMI ' change commata in quotation to temporary semicolons
Next i
sTemp = b ' convert bytes to normal string type
' [2] split as usual
Dim splitStr As Variant
splitStr = Split(sTemp, ",")
' [3] check all results
For i = 0 To UBound(splitStr) ' list all splitted items and ...
Debug.Print i, Replace(splitStr(i), ";", ",") ' ... change semicolons back to normal commata
Next i
End Sub
'Results in immediate window
'---------------------------
'0 str1
'1 "str2,str3"
'2 str4
'3 str5
'4 str6
注意
当然,变量string1
和sTemp
中有一些故意冗余,可以进行其他测试:-)