首页 > 解决方案 > 使用 AUTOFILTER 将过滤后的数据复制到没有标题行的列表底部(不同的 Excel 工作表)

问题描述

我正在使用 AUTOFILTER 过滤一个 Excel 工作表(Input_Wkr_Hrs)上的数据,并将数据附加到同一工作簿中另一个工作表(输出)上的列表(表)的底部。我遇到的问题是,当数据被添加到列表底部时,它包括标题行名称。如何使用 AUTOFILTER 复制过滤后的数据,并且在附加到列表底部时不包含标题名称?

工作表上的源表 (Input_Wkr_Hrs) 具有三列(Emp Name、Section、Hours)。

我正处于学习 Excel VBA 的初级阶段;这是我在 Stackoverflow 上的第一个问题。 下面的代码

Sub GetWorkerData() ' shImput_Wkr_Hrs name if source data sheet ' shOutout name of destination sheet Dim rg As Range Set rg = shImput_Wkr_Hrs.Range("C15").CurrentRegion ' 'TurnOffFunctionality ' 关闭屏幕更新和其他东西

With rg
    .AutoFilter field:=3, Criteria1:=">0"    ' filter working hrs hours >0
    .SpecialCells(xlCellTypeVisible).Copy    'Destination:=shOutput.Range("a1")
    '
    '.Offset(1).Resize(Selection.Rows.Count - 1).SpecialCells(xlCellTypeVisible).Copy
    shOutput.Cells(Rows.Count, 1).End(xlUp).Offset(1).PasteSpecial xlPasteValues

' rg.AutoFilter End With ' shOutput.Activate 'TurnOnFunctionality ' 打开屏幕更新和其他东西 End Sub

标签: excelautofilter

解决方案


假设 ws_Data 包含您要过滤/复制的数据,并且 ws_Output 是将粘贴数据的工作表。

Dim rng_Visible as Range, outputLastRow as long
' Assume that the first line is the header
With ws_Data
    .Range("A1").AutoFilter Field:=3, Criteria1:=">0"

    ' Check if there is data to copy
    If .AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible).Cells.Count - 1 > 0 Then
        Set rng_Visible = .AutoFilter.Range.Offset(1, 0).Resize(.AutoFilter.Range.Rows.Count - 1).SpecialCells(xlCellTypeVisible)
        ' Copy the visible filtered range
        rng_Visible.Copy

        ' Find the last row in Output worksheet using column A, make sure the column you use does not have any blank value in middle
         outputLastRow= ws_Output.Cells(ws_Output.Rows.Count, "A").End(xlUp).Row

         ' Paste to the output worksheet starting from column A
         ws_Output.Range("A" & outputLastRow).PasteSpecial xlPasteAll
         Application.CutCopyMode = False

         ' Turn off the auto filter 
         ws_Data.AutoFilterMode = False
    End If

End With

推荐阅读