像這樣的東西應該可以工作,而且不復雜。您可以使用額外的參數與查找功能也可以指定搜索位置:
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
我要建議搜索姓名來確定列數,但是這可能是更好的使用ADO來讀取csv文件使用SQL'SELECT'聲明解決了 - 這樣你可以有一致的數據進入一致的列。 – YowE3K
YowE3K你有機會擁有如何與ADO做到這一點的任何資源?至於原文,我建議考慮使用.Range.Find()方法來搜索給定的列,然後將這些列存儲在範圍中。我看看我是否可以稍微發表一個例子。 –
@BrandonBarney - 我可以創建一個例子,但明天我上班時會更容易。 (我們在工作中使用SQL來讀取CSV文件,但我很少需要在家裏做同樣的事情 - 我的銀行甚至不會在CSV文件中添加列標題!) – YowE3K