从筛选的数据复制行并插入到现有数据中

我试图复制行数据(可能会或可能不会被过滤),并将其插入到现有数据上方的行(滚动时间表sorting)。 下面是我的代码,适用于未经过滤的数据。 如果我将任何filter应用于要复制的数据,我的macros将只复制1个单元格。 任何人都可以提供一个macros的例子,可以复制过滤和未经过滤的数据?

Sub DynamicRange() 'Best used when first column has value on last row and first row has a value in the last column Dim sht As Worksheet Dim LastRow As Long Dim LastColumn As Long Dim StartCell As Range Dim SelectedRange As Range Set sht = ActiveWorkbook.ActiveSheet Set StartCell = Range("C9") If IsEmpty(StartCell.Value) = True Then MsgBox "Enter Dates to export" Exit Sub End If 'Find Last Row and Column LastRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row LastColumn = sht.Cells(StartCell.Row, sht.Columns.Count).End(xlToLeft).Column 'Select Range and Copy Set SelectedRange = sht.Range(StartCell, sht.Cells(LastRow, LastColumn)) SelectedRange.Select Selection.SpecialCells(xlCellTypeVisible).Select Selection.Copy 'Select sheet "TRACKER" insert values above previous data Sheets("TRACKER").Select Range("B9").Select Selection.Insert Shift:=xlDown 'clear selection Application.CutCopyMode = False End Sub 

我已经重写了你的子程序,并试图避免使用.SelectSelection 。 依赖像ActiveCell¹和ActiveSheet¹这样的属性是最好的。

 Sub DynamicRange() Dim sc As Range, sht As Worksheet Set sht = ActiveWorkbook.Worksheets("Sheet1") '<~~ set this worksheet reference properly 'btw, if you really needed ActiveWorkbook here then you would need it with Worksheets("TRACKER") below. With sht Set sc = .Range("C9") 'don't really have a use for this If IsEmpty(.Range("C9")) Then MsgBox "Enter Dates to export" Exit Sub End If With .Range(.Cells(9, 3), .Cells(9, Columns.Count).End(xlToLeft)) With Range(.Cells(1, 1), .Cells(Rows.Count, .Columns.Count).End(xlUp)) 'got the range; determine non-destructively if anything is there If CBool(Application.Subtotal(103, .Cells)) Then 'there are visible values in the cells .Cells.Copy _ Destination:=Worksheets("TRACKER").Cells(Rows.Count, 2).End(xlUp).Offset(1, 0) End If End With End With End With End Sub 

工作表的SUBTOTAL函数不会计算隐藏值,所以对于可见值的存在来说,这是一个很好的非破坏性testing。 您不需要特别复制Range.SpecialCells与xlCellTypeVisible属性 。 常规的Range.Copy方法只会复制可见的单元格。 通过立即指定目的地,不需要将ActiveSheet属性传递给TRACKER工作表; 只需要指定目标的左上angular。


¹ 请参阅如何避免使用在Excel VBAmacros中select更多的方法来摆脱依靠select和激活来实现您的目标。