由逗号和换行符/回车符

时间:2016-06-17 23:17:09

标签: vba excel-vba csv parsing excel

我已经搜索过每个可用的论坛。我挣扎着。我使用REST api调用来提取动态报告,并且我得到的响应文本包含每个条目双引号和逗号分隔,并且每行都有换行符。

E.g。 -

"Employee ID","Name","Hours"
"123","John Doe","8:00"

我无法执行替换命令,因为某些属性不可避免地会有逗号或双引号。

当前的方法是SPLIT成一个数组,其分隔符为","但我能得到的最好看起来还是这样!

"Employee ID Name        Hours"
"123                John Doe  8:00  "

基本上中间分隔符是由处理的,但我在每一行都留有前导和尾随双引号。

2 个答案:

答案 0 :(得分:0)

这会使用制表符替换分隔符(",")并拆分行

很难确切地知道你想从输出中得到什么,但至少现在你应该能够操纵你想要的线和数据字段。

sub ConvertData(strData as string)    
    Dim varLines    As Variant
    Dim strLine     As String
    Dim lngCounter  As Long
    Dim intField    As Integer

    strData = """Employee ID"",""Name"",""Hours""" & vbCrLf & """123"",""John Doe"",""8:00"""

    ' Retrieve each line
    varLines = Split(strData, vbCrLf)
    For lngCounter = LBound(varLines) To UBound(varLines)

        strLine = CStr(varLines(lngCounter))
Debug.Print "Original Line: " & strLine

        strLine = Replace(strLine, """,""", vbTab)

Debug.Print "After removing delimiters: " & strLine

        strLine = Mid(strLine, 2, Len(strLine) - 2)
Debug.Print "After removing end quotes: " & strLine

    Next lngCounter
end sub

这是Debug打印出来的(每个字段之间有一个标签)

Original Line: "Employee ID","Name","Hours"
After removing delimiters: "Employee ID Name    Hours"
After removing end quotes: Employee ID  Name    Hours
Original Line: "123","John Doe","8:00"
After removing delimiters: "123 John Doe    8:00"
After removing end quotes: 123  John Doe    8:00

答案 1 :(得分:0)

'Split csv
SplitCSVReport = Split(CSVReport, Chr(34) & vbCrLf)
For i = LBound(SplitCSVReport) To UBound(SplitCSVReport)
    CSVSplit = Split(SplitCSVReport(i), Chr(34) & ",")
        For v = LBound(CSVSplit) To UBound(CSVSplit)
        With Cells(15, 15)
            Range(.Offset(i, v), .Offset(i, v)) = Mid(CSVSplit(v), 2, Len(CSVSplit(v)))
            End With
        Next v
Next i