将数据导入excel的更简单方法 – 集合?

有没有更容易的方法将数据导入到Excel数组或其他数据结构? 我试过研究集合,但是我发现文档很难理解。 http://www.functionx.com/vbaexcel/objects/Lesson6.htm

https://msdn.microsoft.com/en-us/library/f26wd2e5%28v=vs.100%29.aspx

我有下面的代码打开一个select文件,search列标题,然后根据头和行variables循环存储数据的每一行,我已经完成了这个方法的许多macros过去,但现在我正在处理很多很多专栏,我正在寻找更先进的方式?

Sub Import_NAVRec() MyPath = Range("b2") 'Defines cell that contains path to source file Workbooks.Open (MyPath) 'Opens file Set tempbook = ActiveWorkbook 'Names workbook LR = Range("A65000").End(xlUp).Row 'finds last row in sourcefile ReDim aNavRec(1 To LR, 1 To 4) 'Defines NAV Rec array nRow = 0 cName = "Accounting Basis" CA = Cells.Find(What:=UCase(cName), After:=ActiveCell, LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext).Column cName = "Accounting Date" cB = Cells.Find(What:=UCase(cName), After:=ActiveCell, LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext).Column cName = "Asset Currency" cC = Cells.Find(What:=UCase(cName), After:=ActiveCell, LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext).Column For r = 2 To LR 'If Cells(r, cB) = "Trading Gain Loss" Then nRow = nRow + 1 aNavRec(nRow, 1) = Cells(r, CA) 'Fund Number aNavRec(nRow, 2) = Cells(r, cB) 'Ledger aNavRec(nRow, 3) = Cells(r, cC) 'Balance change 'End If Next r tempbook.Close End Sub Sub Print_output() Sheets("Output").Select Set Destination = Range("a2") Destination.Resize(UBound(aNavRec, 1) + 1, UBound(aNavRec, 2)).Value = aNavRec End Sub 

我们可以帮助你消除的唯一的东西就是代码中间的for循环。 其余的似乎是必要的。

 Option Explicit Sub Import_NAVRec() Dim LR As Long Dim MyPath As String Dim aNavRec As Variant 'Defines NAV Rec array Dim tempbook As Workbook Dim CA As Long, cB As Long, cC As Long MyPath = Range("B2") 'Defines cell that contains path to source file Workbooks.Open (MyPath) 'Opens file Set tempbook = ActiveWorkbook 'Names workbook LR = Range("A65000").End(xlUp).Row 'finds last row in sourcefile cName = "Accounting Basis" CA = Cells.Find(What:=UCase(cName), After:=ActiveCell, LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext).Column cName = "Accounting Date" cB = Cells.Find(What:=UCase(cName), After:=ActiveCell, LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext).Column cName = "Asset Currency" cC = Cells.Find(What:=UCase(cName), After:=ActiveCell, LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext).Column aNavRec = Application.Index(Range("A:AZ"), Application.Evaluate("Row(1:" & LR & ")"), Array(CA, cB, cC)) tempbook.Close End Sub 

随着Option Explicit更多的Dim是必要的(我包括在上述解决scheme)。

注意:在这里find这个解决scheme: 使用row_num application.indexvariables