VBA如何在双引号内使用breakline读取CSV?

时间:2018-01-09 03:45:10

标签: excel vba excel-vba csv

我尝试在引号(data.csv)中上传带有分隔线的CSV file,但不是将所有文本放在引号中的一个单元格中,它仍将其视为新行。< / p>

当我直接打开CSV时,一切正常,但是当我通过VBA运行时,一切都搞砸了。

data.csv示例

cases,"variant:
option1: 0333102
option2: 1133202
option3: 4234442"
make-shift,"variant:
option1: shift iron
option2: workload
option3: network map
option4: lesson map"

Import_CSV功能

Function import_CSV(location As String, row As Integer, col As String) As Variant

Dim ws As Worksheet, strFile As String
Sheets("data").Visible = True

Sheets("data").UsedRange.ClearContents

Set ws = Sheets("data")
strFile = location

With ws.QueryTables.Add(Connection:="TEXT;" & strFile, Destination:=ws.Range("A1"))
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 850
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = False
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
End With

import_CSV = Sheets("data").Range(col & "1:" & Get_C(Last_C(row, "data")) & Last_R(Get_C(Last_C(row, "data")), "data"))
Sheets("data").Visible = False

End Function

1 个答案:

答案 0 :(得分:1)

假设您的import_CSV()返回数据工作表中与导入的CSV大小相同的范围,请尝试以下操作。不是真的需要row整数和col字符串,所以我省略了它。

Option Explicit

Function ImportCustomCSV(location As String) As Range
    Dim oWbCSV As Workbook, oRngCSV As Range, oRngData As Range
    ThisWorkbook.Worksheets("data").UsedRange.ClearContents
    ' Range to start pasting csv data
    Set oRngData = ThisWorkbook.Worksheets("data").Range("A1")
    ' Assumes file availability is already checked
    Set oWbCSV = Workbooks.Open(Filename:=location, ReadOnly:=True)
    Set oRngCSV = oWbCSV.Worksheets(1).UsedRange
    ' Copy the CSV range to data worksheet
    oRngCSV.Copy oRngData
    ' Make the data range the same rows and cols as imported csv
    Set oRngData = oRngData.Resize(oRngCSV.Rows.Count, oRngCSV.Columns.Count)
    ' Cleanup
    Set oRngCSV = Nothing
    oWbCSV.Close SaveChanges:=False
    Set oWbCSV = Nothing
    ' Return the updated data range
    Set ImportCustomCSV = oRngData
End Function