這是一個有趣的問題,我想出了一個通用函數,它可以用於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()
函數。
然後我遍歷所得到的數組,並用逗號替換所有replacementCharacters。
我測試使用給出了具體的例子,混合引述逗號值的更一般的示例值我的代碼,並且:
代碼:
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
此功能的任何數量的包含引用字符串的逗號,以任意順序排列。
感謝詳細的解答。我試圖整合它,但是由於某種原因它沒有工作。值0,1和2仍然相同,1和2不分組。 你知道可能是什麼原因嗎?請給我一些關於實際與我的完整代碼整合的指導? 謝謝! – Newskooler