这是一个有趣的问题。我想出了一个通用函数,它适用于 csv 行中任意数量的非引用和引用值,其中引用的值可能包含也可能不包含逗号。
测试线: "Penn National Gaming, Inc.",16.28
输出:
Value[0] = Penn National Gaming, Inc.
Value[1] = 16.28
测试线: a,b,c,"some, commas, here",16.28,"some,commas,there",17.123
输出:
Value[0] = a
Value[1] = b
Value[2] = c
Value[3] = some, commas, here
Value[4] = 16.28
Value[5] = some,commas,there
Value[6] = 17.123
我首先在该行中搜索了成对的引号“...”。
在每对引号中,我搜索了逗号,并将它们替换为我认为永远不会正常出现的字符,replacementCharacter = "¯",(如果需要,您可以选择不同的字符)。
替换引用的逗号后,我使用Split() 函数将行分隔为逗号。
然后我遍历生成的数组并将所有替换字符替换为逗号。
我使用给出的具体示例和一个更一般的混合引号逗号值和值的示例测试了我的代码:
代码:
Function parseLine(sLine)
Dim Value As Variant
Dim i As Integer
quote = """"
delimiter = ","
replacementCharacter = "¯"
'get first pair of quotes
currentQuoteIndex = InStr(1, sLine, quote) 'get first quote
If (currentQuoteIndex = 0) Then
nextQuoteIndex = 0
Else
nextQuoteIndex = InStr(currentQuoteIndex + 1, sLine, quote) 'get next quote
End If
'get pairs of quotes and replace commas with replacementCharacter
Do While nextQuoteIndex <> 0 And currentQuoteIndex <> 0
subString = Mid(sLine, currentQuoteIndex + 1, nextQuoteIndex - currentQuoteIndex - 1)
subString = Replace(subString, comma, replacementCharacter)
sLine = Left(sLine, currentQuoteIndex - 1) + subString + Right(Mid(sLine, nextQuoteIndex + 1), Len(sLine))
'get next pair of quotes
currentQuoteIndex = InStr(nextQuoteIndex + 1, sLine, quote) 'get first quote
If (currentQuoteIndex = 0) Then
nextQuoteIndex = 0
Else
nextQuoteIndex = InStr(currentQuoteIndex + 1, sLine, quote) 'get next quote
End If
Loop
'split string by commas
Values = Split(sLine, delimiter)
'replace replacementCharacter with commas
For i = 0 To UBound(Values)
Values(i) = Replace(Values(i), replacementCharacter, delimiter)
Next
parseLine = Values
End Function
此函数适用于包含引号字符串的任意数量的逗号,列的顺序不限。