2012-04-22 46 views
4

我正在使用下面的VBA代碼在Excel中打開一個csv文件(代碼模擬Data \ Text to Columns - 命令)。在代碼中,需要爲屬性TextFileColumnDataTypes指定一個數組,這對於csv文件中的每一列都指定了數據格式(2 =文本格式)。使用TextFileColumnDataTypes以正確的數據格式爲每列打開CSV文件?

但是,由於我不知道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

這裏是從一個封閉的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 
+0

Thx詳細說明!關於第二種解決方案,就我所見,基本上只刪除了關於逗號和千位分隔符的兩行,並將屬性TextFilePlatform更改爲1252.但是,此代碼對我無效。例如。它將「03/08/2012」轉換爲日期。關於第一種解決方案,讀出符合要求的列數。感謝你的代碼!然而,我想知道是否有更自然的解決方案來填充存儲在屬性TextFileColumnDataTypes中的信息,然後給出一個固定長度的數組...... – tyrex 2012-04-23 07:34:47

1

爲我的作品的骯髒的方法是初始化一個更大的數據類型的數組比以往任何時候都需要。剩餘列數據類型被忽略。

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 
相關問題