0

我有一张有 200 行的表格,中间有一些空白。

我无法使用End(xlDown)End(xlUp)获取整个范围,因为有空白行。

如何复制到最后一个在列中有数据的范围?

另外,我不想复制标题。

请建议我如何在 Excel VBA 中做到这一点。

4

2 回答 2

8

复制它们的最佳方法是使用自动过滤器并在空白处过滤它们,然后复制可见范围

例如

Sub Sample()
    Dim ws As Worksheet
    Dim lRow As Long
    Dim rngToCopy As Range, rRange As Range

    Set ws = Sheets("Sheet1")

    With ws
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row

        Set rRange = .Range("A1:A" & lRow)

        '~~> Remove any filters
        .AutoFilterMode = False

        With rRange 'Filter, offset(to exclude headers) and copy visible rows
            .AutoFilter Field:=1, Criteria1:="<>"
            Set rngToCopy = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
        End With

        '~~> Remove any filters
        .AutoFilterMode = False

        rngToCopy.Copy

        '
        '~~> Rest of the Code
        '
    End With
End Sub
于 2012-07-10T16:03:20.277 回答
4

You can get the last used row in column A of the active sheet with the code below (it works also if you have blank cells in the middle of the column) - amend as required if you need to run it on a different sheet / column.

With ActiveSheet
    lastRow = .Range("A" & .Rows.Count).End(xlUp).Row
    .Range("A2:A" & lastRow).Copy 'copies column A used range, excluding header row
End With
于 2012-07-10T15:38:21.017 回答