2017-02-11 17 views
0

現在、Excelの自動インポートによってExcelにインポートされているマクロの銀行口座からエクスポートされた.csvファイルがあります(一部の列の削除、コンカット、等。何も特別)。CSVからのインポート先と場所を選択するExcelマクロ

ただし、.csvファイルに一貫性のあるフォーマットがなく、その場所を変更する列があります(たとえば、列「IBAN」が列2、時には列5になることもあります)私のマクロがクラッシュする原因になります。

私が必要とするのは、.csvで最初に動作するコードです。.csvで列 "IBAN"をチェックし、チェック後にインポートするので、いつも列noと言います。 1と私のマクロは列番号を処理します。 1問題なし。

アイデア?

+0

私は列番号を決定するための名前を探し示唆するつもりだったが、これはおそらく、より良いSQL 'SELECT'ステートメントを使用してcsvファイルを読むためにADOを使用することによって解決している - あなたは一貫性のあるデータを持っている可能性があり、その方法が入ります一貫性のある列。 – YowE3K

+0

YowE3K偶然、ADOでこれを行う方法に関するリソースがありますか?元の投稿については、.Range.Find()メソッドを使用して特定の列を検索し、これらの列を範囲に格納することを検討することをおすすめします。私が少し例を投稿できるかどうかを見てください。 –

+0

@BrandonBarney - 私は例を作ることができましたが、明日仕事をするともっと簡単になります。 (私たちはSQLを使用してCSVファイルをたくさん読んでいますが、家でも同じことをする必要はほとんどありません - 私の銀行は列見出しをCSVファイルに入れていません!) – YowE3K

答えて

1

このようなものはうまくいくはずであり、むしろ複雑ではありません。あなたが検索している場所を指定するだけでなく、検索機能を追加の引数を使用することができます。

Public Function GetColumnRange(ByVal sSearch As String, r As Object, rSearchArea As Range) 
If Not rSearchArea.Find(sSearch, , , xlWhole) Is Nothing Then 
    Set r = rSearchArea.Find(sSearch, , , xlWhole) 
    r.Select 
    GetColumnRange = True 
End If 

エンド機能 公共サブCSV_Reformat() 薄暗いWBは、ワークシート

Dim arrArgs() As Variant 

Dim cColl As Collection 

Dim rHolder As Object 

Set cColl = New Collection 
arrArgs() = Array("IBAN", "Arg2", "Arg3") 

' Use the code you have to load the .CSV file and to open it 
' Assumes that wb is set to the .CSV file 
' Assumes ws is the first sheet in the .CSV file 

Set wb = ActiveWorkbook ' Replace this with your actual .CSV file 
Set ws = wb.Sheets(1) 

For i = LBound(arrArgs()) To UBound(arrArgs()) 
    If GetColumnRange(arrArgs(i), rHolder, ws.UsedRange) = True Then 
     cColl.Add rHolder 
    End If 
Next 

For i = 1 To cColl.Count 
    Set rHolder = cColl(i) 

    ' Do whatever you need to do with the range here 
    ' For example, you could get the column number: 

    Debug.Print rHolder.Column 
Next 

End Sub 

としてブック 薄暗いWSとして私はあなたのCSVファイルが大きい場合は、このための配列を使用することを検討することをお勧めします。あなたは使用して、配列を読み込むことができます。

Dim arrData() as Variant 
Dim i as Long, Dim j as Long 
Dim lOutput as Long 
Dim bool as Boolean 

' Assumes, as before, that ws is the worksheet we are working in 

arrData() = ws.UsedRange.Value 

あなたは、このような出力の何かのために新しい配列を作成することができます。

Dim arrOut() as Variant 

redim arrOut(0 to Ubound(arrData()) - 1, 0 to i) 

' Reduce it by one row since we are creating a zero based array. i is the 
' number of columns you want in the output. 

' Then loop over the data array and put the right columns into your output 

For i = 1 to Ubound(arrData(), 2) ' Loop through the headers in your data 
    bool = True 
    Select Case arrData(1, i) 
     Case "IBAN" 
      lOutput = 0 ' Allows you to determine where the data will be put in your array 
     Case "Arg2" 
      lOutput = 1 
     Case "Arg3" 
      lOutput = 2 
     Case Else 
      bool = False 
    End Select 

    If bool = True Then 
     For j = 1 to Ubound(arrData(), 1) 
      arrOut(j - 1, lOutput) = arrData(j, i) 
     Next 
    End If 
Next 

これは、.csvファイルや負荷から特定のデータを選択できるようにする必要がありますそれを配列に変換します。必要に応じて範囲にデータを出力することができます。例

With wsOutput 
    Set r = .Range("A1").Resize(Ubound(arrOut(), 1) + 1, Ubound(arrOut(), 2) + 1) 
    r.Value = arrOut() 
End With 
0

のために以下のコードは、このようにあなたがそれらをしたいた順序で、あなたが望むだけの列をインポートし、CSVファイルにSQLクエリを実行するためにADODBを使用しています。

Sub SQL_Extract() 
    Dim objConnection   As Object 
    Dim objRecordset   As Object 
    Dim CSVFilename    As String 
    Dim CSVFilepath    As String 

    CSVFilename = "myCSVFile.csv"   ' Change to name of your CSV file 
    CSVFilepath = "C:\Temp\DownloadFolder\" ' Change to location of CSV file 

    ' Set up connections & dataset objects 
    Set objConnection = CreateObject("ADODB.Connection") 
    Set objRecordset = CreateObject("ADODB.Recordset")  
    objConnection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _ 
            "Data Source=" & CSVFilepath & ";" & _ 
            "Extended Properties=""text;HDR=YES;FMT=CSVDelimited"";" 
    objConnection.Open 

    'Create the SQL command to retrieve information 
    'The following assumes that the CSV file contains columns with headings of 
    ' "IBAN", "Transaction Date" and "Amount". (Any other columns in the file 
    ' will be ignored.) 
    sqlCommand = "SELECT [IBAN], " & _ 
       "  [Transaction Date], " & _ 
       "  [Amount] " & _ 
       "FROM [" & CSVFilename & "]" 
    'Execute the query 
    objRecordset.Open sqlCommand, objConnection, 3, 3, 1 

    If Not objRecordset.EOF Then ' Check whether any records were created by the query 
     ' Write out the results of the query 
     ' Change "A2" to top left cell of area where you want results written 
     Range("A2").CopyFromRecordset objRecordset 
    End If 

    objRecordset.Close 
    objConnection.Close 
End Sub 
関連する問題