how to auto-copy rows to new sheet VBA Excel

前端 未结 1 1136
难免孤独
难免孤独 2021-01-27 22:27

I\'m trying to auto-copy a row from a master spreadsheet to another spreadsheet. This should occur when the input value in th

相关标签:
1条回答
  • 2021-01-27 23:13

    I guess you start clearing "X" sheet from row 2 to preserve headers

    should this be the case, you can clear all "X" sheet rows and paste headers form "Master" sheet back

    Option Explicit
    
    Sub FilterAndCopy()
        Dim sht1 As Worksheet, sht2 As Worksheet
    
        Set sht1 = Sheets("Master")
        Set sht2 = Sheets("X")
    
        sht2.UsedRange.ClearContents
        Dim rng As Range
    
        With sht1.Cells(1, 1).CurrentRegion
            .AutoFilter
            .AutoFilter 1, "X"
            For Each rng In .SpecialCells(xlCellTypeVisible).Areas ' loop through visible cells "groups"
                rng.Copy sht2.Range(rng.Address) ' copy current group and paste it to 'sht2' (i.e. sheet "X") corresponding address
            Next
            .AutoFilter
        End With
    
        With sht2.UsedRange ' reference 'sht2' used range
            .Columns(1).SpecialCells(xlCellTypeBlanks).EntireRow.Delete ' delete referenced sheet blank rows
            .Rows(1).SpecialCells(xlCellTypeBlanks).EntireColumn.Delete ' delete referenced sheet blank columns
        End With
    End Sub
    

    Edited to account for possible "Master" sheet hidden columns

    0 讨论(0)
提交回复
热议问题