2012-04-22 6 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のコードを修正する必要があります)行1 CSVにおけるヘッダ(カラムのいずれかに少なくとも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 

EDIT

はまた、ここに私の作品汚いやり方が今までに必要なよりもはるかに大きなデータ型の配列を初期化することですはるかに簡単な方法(私は前にそれを考えていなかった理由を疑問に思う...)

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! 2番目の解決策に関しては、私が見る限り、基本的にはコンマと千単位区切りに関する2行を削除し、プロパティTextFilePlatformを1252に変更しました。しかし、このコードは私のためには機能しませんでした。例えば。 「03/08/2012」を日付に変換します。最初の解決策に関しては、列の数を読み出すことは正式に機能します。そのコードをありがとう!しかし、TextFileColumnDataTypesプロパティに格納された情報にデータを埋め込んでより固定長の配列を与えるより自然な解決策があるのだろうかと疑問に思った。 – tyrex

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 
関連する問題