2017-02-11 140 views
0

我從我的銀行帳戶導出了一個.csv文件,該文件當前正通過Excel導入到Excel自動導入,然後使用我的宏進行處理(某些列刪除,格式更改, concat等等。沒什麼特別的)。Excel宏選擇從CSV導入的內容和從哪裏導入

但是,.csv文件沒有一致的格式,並且有些列會改變它們的位置(例如,列「IBAN」有時是第2列,有時是第5列)或根本不存在,這會導致我的宏崩潰。

我需要的是一些代碼,它將首先與.csv一起工作,檢查列「IBAN」的.csv並在檢查後導入它,所以總是讓我們說列號。 1和我的宏將處理列號。 1沒有問題。

任何想法?

+0

我要建議搜索姓名來確定列數,但是這可能是更好的使用ADO來讀取csv文件使用SQL'SELECT'聲明解決了 - 這樣你可以有一致的數據進入一致的列。 – 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 

端功能 公用Sub CSV_Reformat() 昏暗WB作爲工作簿 昏暗的WS作爲工作表

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 

如果您的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

下面的代碼使用ADODB對CSV文件執行一個SQL查詢,從而導入只是你想要的列,在您想要的順序。

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