0

我从每个工作表中获取 AK 列中的数据并将其放入单个工作表中。我的代码现在正确地抓住了第一张纸,但在那之后它什么也没得到。老实说,我不知道为什么。

这是我现在的代码:

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

对缺乏评论表示歉意,这是我下次可能应该添加的内容。所以有人知道我哪里出错了吗?

4

2 回答 2

1

您需要对代码进行以下更正:

Set destRange = destRange.End(xlDown)
Set destRange = destRange.Offset(1, 0)

您指的是srcRange而不是destRange,因此它只是过度复制了相同的范围(在其他工作表中)。

于 2013-09-08T19:41:57.097 回答
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
于 2013-09-08T19:42:12.430 回答