我从每个工作表中获取A-K列中的数据并将其放入单个工作表中。我现在的代码是正确地抓取第一张纸,但之后没有得到任何东西。老实说,我不明白为什么。
这是我现在的代码:
Sub compile()
Dim srcRange, destRange As Range
Dim wkSheet As Worksheet
Dim wksheet_number, lastRow As Long
wksheet_number = 1
For Each wkSheet In ThisWorkbook.Worksheets
If wksheet_number > 1 Then
lastRow = ThisWorkbook.Worksheets(wksheet_number).Cells(Rows.Count, "A").End(xlUp).Row
Set srcRange = ThisWorkbook.Worksheets(wksheet_number).Range("A2:K" & lastRow)
Set destRange = ThisWorkbook.Worksheets(1).Range("A2")
If destRange.Value = "" Then
srcRange.copy destRange
Else
Set destRange = srcRange.End(xlDown)
Set destRange = srcRange.Offset(1, 0)
'destRange.Select
srcRange.copy destRange
End If
wksheet_number = wksheet_number + 1
Else
wksheet_number = wksheet_number + 1
End If
Next wkSheet
End Sub
对于缺乏评论的道歉,这是我下次应该添加的内容。所以任何人都知道我哪里出错了?
答案 0 :(得分:1)
您需要对代码进行以下更正:
Set destRange = destRange.End(xlDown)
Set destRange = destRange.Offset(1, 0)
您指的是srcRange
而不是destRange
,所以它只是过度复制相同的范围(在其他工作表中)。
答案 1 :(得分:1)
我同意@Andy G.这是您的程序的另一个更短的版本。由于循环遍历工作簿中的每个工作表,因此不需要使用wksheet_number
变量。您可以在循环的每次迭代中直接使用wkSheet
对象。
Sub compile()
Dim srcRange, destRange As Range
Dim wkSheet, sheetDestination As Worksheet
Dim columnCount, lastRow As Long
rowCount = 2 'Starting at A2
Set sheetDestination = ThisWorkbook.Worksheets(1) 'Also could use the name like ThisWorkbook.Worksheets("MyReport")
For Each wkSheet In ThisWorkbook.Worksheets
If Not wkSheet = sheetDestination Then
lastRow = wkSheet.Cells(Rows.Count, "A").End(xlUp).Row
Set srcRange = wkSheet.Range("A2:K" & lastRow)
Set destRange = sheetDestination.Range("A" & rowCount)
srcRange.Copy destRange
rowCount = rowCount + lastRow + 1
End If
Next wkSheet
End Sub