我的问题是关于收藏集的。
在这段代码中,我在当前excel的文件夹中打开彼此的excel,然后将其第一列的所有数据检索到集合中。
然后,我尝试将收集的值插入当前文件中。
当我使用coll.count时,该计数是正确的,因此我认为数据已被有效收集。
我以前使用过'Sheet.cells.value = coll(i)'的形式,并且运行良好,但是在这种情况下却没有。
出现错误1004-该行中显示“运行时错误'1004':应用程序定义的错误或对象定义的错误”。
您对为什么有任何想法吗? 有什么建议吗?
谢谢!
Option Explicit
Sub LoopThroughFolder()
Application.ScreenUpdating = False
'State variables
Dim Path As String 'path of folder
Dim DataBase As String ' current excel file
Dim ERow As Long 'last row of current excel file
Dim coll As New Collection 'collection of data
Dim iRow As Long 'rows of other excel files
Dim n As Long 'total records of other excel files
Dim i As Integer
'Name of files to open
Path = Dir(ActiveWorkbook.Path & "\")
DataBase = ActiveWorkbook.Name
'For each file
Do While Path <> DataBase
'Open, retrieve data, close
Workbooks.Open (ActiveWorkbook.Path & "\" & Path)
n = Application.WorksheetFunction.CountA(Range("A:A"))
For iRow = 2 To n
coll.Add Cells(iRow, 1)
Next iRow
ActiveWorkbook.Close
'Next file
Path = Dir
Loop
'Now place the values in my current excel file (here is the problem)(?)
ERow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row
For i = 1 To coll.Count
ActiveSheet.Cells(ERow + i, 1).Value = coll(i)
Next i
'End
Set coll = Nothing
Application.ScreenUpdating = True
End Sub
答案 0 :(得分:0)
替换:
ActiveSheet.Cells(ERow + i, 1).Value = coll(i)
具有:
ActiveSheet.Cells(ERow + i, 1).Value = coll.Item(i)
(可能还有其他问题)
答案 1 :(得分:0)
请将coll.Add Cells(iRow, 1)
更改为coll.Add Cells(iRow, 1).Value
,它将开始工作。
最好在第一个dir语句中添加一些通配符,例如'Path = Dir(ActiveWorkbook.Path & "\*.xlsx")
'
一旦遇到数据库,Do While Path <> DataBase
也可能导致终止循环。最好像这样
Do While Path <> ""
If Path <> DataBase Then
'''''''''''''''
''''''''''''''
End If
Path = Dir
Loop