4

我正在使用下面的 VBA 代码在 Excel 中打开一个 csv 文件(代码模拟 Data\Text to Columns - 命令)。在代码中,必须为属性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
4

2 回答 2

3

这是一种无需在 Excel 中打开即可从已关闭的 CSV 中查找列数的方法。

我假设以下。

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
于 2012-04-22T16:21:45.317 回答
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
于 2014-11-30T15:12:01.467 回答