简体   繁体   中英

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. There would not be anymore than 20 rows.

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).

If the data to be copied is after the first 20 rows, I get a 1004 error. The filter does find that there is data however my copy code is only looking at the first 20 rows.

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")? 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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