与使用TextFileColumnDataTypes每列数据格式正确打开CSV文件?(Open CS

2019-09-16 16:02发布

我使用的VBA代码以下在Excel中打开一个CSV文件(代码模拟数据\文本分列 - 命令)。 在代码有必要指定属性TextFileColumnDataTypes,这对于在CSV文件每列指定的数据格式(2 =文本格式)的阵列。

然而,因为我不知道该CSV文件将有多少列有,我想指定在CSV文件中的所有列的格式2(=文本格式)。 现在的问题是,我只能指定为固定数量的列的数据格式(在下面的例子中它是3列)。

解决这个问题的任何帮助,高度赞赏:)

===============================================

下面是我使用的完整的代码:


    With ThisWorkbook.Worksheets(1).QueryTables.Add(Connection:= _
        "TEXT;C:\test.csv", Destination _
        :=ThisWorkbook.Worksheets(1).Range("$A$1"))
        .name = "Query Table from Csv"
        .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(2, 2, 2)
        .TextFileDecimalSeparator = "."
        .TextFileThousandsSeparator = ","
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
        .Delete     
    End With

Answer 1:

这里是要找到从一个封闭的CSV列的数量,而不在Excel中打开它的一种方式。

我假设如下。

1)您正在打开一个逗号分隔文件。 如果没有,那么你将不得不适当地修改代码

2)在CSV行1具有集管( 至少1层报头中的任何列的

试试这个(我测试了它,但如果你得到任何错误让我们知道:)

Option Explicit

Const ExlCsv As String = "C:\test.csv"

Sub Sample()
    Dim MyData As String, strData() As String, TempAr() As String
    Dim ArCol() As Long, i As Long

    '~~> Open the text file in one go
    Open ExlCsv For Binary As #1
    MyData = Space$(LOF(1))
    Get #1, , MyData
    Close #1
    strData() = Split(MyData, vbCrLf)

    '~~> Check for any empty headers and replace ",," by ","
    Do While InStr(1, strData(0), ",,") > 0
        strData(0) = Replace(strData(0), ",,", ",")
    Loop

    '~~> Split the headers to find the number of columns
    TempAr() = Split(strData(0), ",")

    '~~> Create our Array for TEXT       
    ReDim ArCol(1 To UBound(TempAr))
    For i = 1 To UBound(TempAr)
        ArCol(i) = 2
    Next i

    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;" & ExlCsv, Destination:=Range("$A$1") _
        )
        .Name = "Output"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 1252
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = ArCol
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
End Sub

编辑

另外,这里是一个更简单的方法(奇怪,为什么没有我以前想的吧...)

Option Explicit

Const ExlCsv As String = "C:\test.csv"

Sub Sample()
    ActiveSheet.Cells.NumberFormat = "@"

    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;" & ExlCsv, Destination:=Range("$A$1") _
        )
        .Name = "Output"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 1252
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False

         '<~~ This doesn't make any difference anymore
        .TextFileColumnDataTypes = Array(2)

        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
End Sub


Answer 2:

这对我的作品的肮脏的方法是初始化一个更大的数据类型的数组比以往任何时候都需要的。 剩余列的数据类型将被忽略。

Sub CSV_Import(strFile As String)
Dim ws As Worksheet
Dim colDataTypesArr(1 to 100) As Long
Dim i As Long

Set ws = Sheet1
For i = 1 To UBound(colDataTypesArr)
    colDataTypesArr(i) = 2
Next i

With ws.QueryTables.Add(Connection:="TEXT;" & strFile, Destination:=ws.Range("A1"))
     .TextFileParseType = xlDelimited
     .TextFileCommaDelimiter = True
     .TextFileTextQualifier = xlTextQualifierDoubleQuote
     .TextFileColumnDataTypes = colDataTypesArr
     .Refresh
End With
End Sub


文章来源: Open CSV file with correct data format for each column using TextFileColumnDataTypes?