執行此類任務的最有效方法是將所有數據加載到數組中,並對數組而不是Excel單元格進行操作。
這是給你的任務,使用數組的代碼(我加了一些評論,所以你應該知道是怎麼回事):
Sub WorksheetLoop()
Dim wkb As Excel.Workbook
Dim wks As Excel.Worksheet
Dim data As Variant
Dim row As Long
Dim cellValue As Variant
Dim nonEmptyCells() As Variant
Dim firstEmptyRow As Long
Dim destinationRange As Excel.Range
'------------------------------------------------------------
Set wkb = Excel.ActiveWorkbook
'Iterate through all the worksheets, search through theirs first column
'and collect data from all non-empty cells into a separate String array
'nonEmptyCells().
For Each wks In wkb.Worksheets
If wks.Name <> "Summary" Then
With wks
Debug.Print wks.Name
'Read data into array and use this array to operate on those
'data later instead of operating directly on Excel cells -
'it will improve performance.
data = .Range(.Cells(1, 1), .Cells(260, 1))
'Iterate through all the values read from the currently
'processed worksheet.
For row = LBound(data, 1) To UBound(data, 1)
'Assign value from array to variable for better readability.
cellValue = data(row, 1)
'If this value is not empty, add it to array nonEmptyCells.
If cellValue <> vbNullString Then
Call addEntry(nonEmptyCells, cellValue)
End If
Next row
End With
End If
Next wks
'At this point all the values from non-empty cells from all worksheets
'are collected in array nonEmptyCells. All we have to do is to paste
'them to worksheet "Summary"
'Check if there are any values in nonEmptyCells. If not, there is nothing
'to be printed out in "Summary" worksheet and we can leave the macro.
If countDimensions(nonEmptyCells) = 0 Then Exit Sub
'Find first empty row in worksheet "Summary".
Set wks = wkb.Worksheets("Summary")
firstEmptyRow = wks.Cells(wks.Rows.Count, 1).End(xlUp).row + 1
Set destinationRange = wks.Cells(firstEmptyRow, 1).Resize(UBound(nonEmptyCells) - LBound(nonEmptyCells), 1)
destinationRange = Application.WorksheetFunction.Transpose(nonEmptyCells)
End Sub
請注意,爲了讓這個宏正常工作,你需要將此功能粘貼到您的代碼中:function for adding new entry to dynamic array。
剪貼板是一個用戶工具,你不應該以編程方式使用它。 –