Correct way to offset headers while looping through a filtered list?

此生再无相见时 提交于 2021-01-29 08:33:15

问题


In the below code i'm trying to use a for loop through a filtered list. Without the offset the loop is going through each field and copying the data multiple times. With the offset its skipping rows.

How can I rephrase this to only loop through each row once, and skip the header row?

        'Offset Placement Wrong
        Set rngVisible = activeSheet.AutoFilter.Range.SpecialCells(xlCellTypeVisible).Offset(1, 0)

        For Each rngCell In rngVisible

                    Rows(rngCell.Row).Select
                    Selection.Copy

                    Sheets(2).Select

                    'Skip Headers
                    Cells(2 + rowsRelocated, 1).Select
                    activeSheet.Paste

                    Sheets(1).Select

                    'row increment
                    rowsRelocated = rowsRelocated + 1

         Next

回答1:


Restrict the range to one column of your filter.

    Dim rngVisible As Range, RowsRelocated As Long, rngCell As Range
    Set rngVisible = ActiveSheet.AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible)
    RowsRelocated = 0

    For Each rngCell In rngVisible.Cells
         If rngCell.Row > 1 Then
            rngCell.EntireRow.Copy Sheets(2).Cells(2 + RowsRelocated, 1)
            RowsRelocated = RowsRelocated + 1
         End If
    Next



回答2:


You can copy all filtered visible data at once from Sheets(1) to Sheets(2)...

Sub test()

Dim allData As Range, FilteredData As Range, rngVisible As Range, TargetRange As Range

Set allData = Sheets(1).Range("A1").CurrentRegion
'Instead of currentregion you could mention actual range if it contains blank rows.
Set FilteredData = allData.Offset(1, 0).Resize(allData.Rows.Count - 1, allData.Columns.Count)
Set rngVisible = FilteredData.Cells.SpecialCells(xlCellTypeVisible)
Set TargetRange = Sheets(2).Range("A1").CurrentRegion.Offset(Sheets(2).Range("A1").CurrentRegion.Rows.Count, 0)
'Assuming that Row 1 in Sheets(2) is header, Copy visible data from A2
rngVisible.Copy TargetRange

End Sub


来源:https://stackoverflow.com/questions/60633612/correct-way-to-offset-headers-while-looping-through-a-filtered-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!