简体   繁体   English

Excel vba 设置自动过滤后要复制的动态范围

[英]Excel vba Set a dynamic range to copy after auto filter

I am attempting to update a sheet ("EditEx") with data from a register sheet ("TK_Register") after a filter is applied based on the reference number.在根据参考号应用过滤器后,我正在尝试使用来自登记表(“TK_Register”)的数据更新工作表(“EditEx”)。 There would not be anymore than 20 rows.不会超过 20 行。

My issue has to do with the copy and paste.我的问题与复制和粘贴有关。

If the data to be copied is in the first 20 rows it copies and pastes the data but also copies blank rows up to Row 21 (as set in my DBExtract range).如果要复制的数据在前 20 行中,它会复制并粘贴数据,但也会将空白行复制到第 21 行(如我的 DBExtract 范围中设置的那样)。

If the data to be copied is after the first 20 rows, I get a 1004 error.如果要复制的数据在前 20 行之后,我会收到 1004 错误。 The filter does find that there is data however my copy code is only looking at the first 20 rows.过滤器确实发现有数据,但是我的复制代码只查看前 20 行。

How can I have the copy filtered rows work dynamically WITHOUT also copying blank rows (which also happens if I set my copy range to be "A:K")?我怎样才能让复制过滤的行在不复制空白行的情况下动态工作(如果我将复制范围设置为“A:K”也会发生这种情况)? Thanks谢谢

    Sub UpdateInputWithExisting()

    ActiveCell.Offset(0, 1).Select
    Set RefID = ActiveCell

    Sheets("TK_Register").Range("A1:N1000").AutoFilter field:=12, Criteria1:=RefID

    Dim DbExtract, DuplicateRecords As Worksheet
    Set DbExtract = ThisWorkbook.Sheets("TK_Register")
    Set DuplicateRecords = ThisWorkbook.Sheets("EditEx")

    DbExtract.Range("A2:K21").SpecialCells(xlCellTypeVisible).copy
    DuplicateRecords.Cells(32, 3).PasteSpecial xlPasteValues
    On Error Resume Next
    Sheets("TK_Register").ShowAllData
    On Error GoTo 0

    ActiveWorkbook.RefreshAll
    Sheets("EditEx").Select
    Range("B13").Select

    MsgBox ("Record Retrieved. Make your changes and ensure you click 'Save Changes' to update the Master Registers")

    End Sub

i would recommend that you change the following two lines to (given that your sheet doesn't have any adjacent data to your table):我建议您将以下两行更改为(鉴于您的工作表没有任何与您的表格相邻的数据):

Sheets("TK_Register").Range("A1").CurrentRegion.AutoFilter field:=12, Criteria1:=RefID 

And this:和这个:

DbExtract.Range("A1").CurrentRegion.SpecialCells(xlCellTypeVisible).copy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM