简体   繁体   中英

How to copy/paste formula in filtered/visible cells via VBA in Excel

I am struggling with copying and pasting formula from one column to another one within using filter in another column.

I got a table with 52 columns (number of rows is changing each month). In column AW (#49) I have applied filter. It shows only CTD . After applying this filter I need to copy formula from column AH to column AG. Of course I need to apply this only for filtered/visible cells. The code I have written is copying/pasting this formula into all cells in column AG (it doesn't consider my filter in column AW). Another problem is that when applying the filter in column AW then the first visible row doesn't need to be all the time AH2 but it can be eg AH15 or whatever. I guess this could be avoid via some dynamic solution. Unfortunately I have no clue how to do it.

Afterwards I would like to apply the same for filters in another columns.

Many warm thanks in advance for any hint! :)

This is my code:

Sub ApplyFilterInColumnAW()

Sheets("DATA").Select
ActiveSheet.ListObjects("tb_DATA").Range.AutoFilter Field:=49, Criteria1:="CTD"
Range("AG2").Select  'dynamic solution?
ActiveCell.FormulaR1C1 = "=[@[Service/Log Formula]]" 'header name of column AH

End Sub

Range.Copy and Range.Paste only work on visible cells. In my example I target the cells in the column using the Column Header.

Sub ApplyFilterInColumnAW()
    Const TagetColumnLabel = "Test"
    Dim tbl As ListObject
    Set tbl = Sheets("DATA").ListObjects("tb_DATA")

    With Sheets("DATA")
        .ListObjects("tb_DATA").Range.AutoFilter Field:=49, Criteria1:="CTD"
        tbl.ListColumns(TagetColumnLabel).DataBodyRange.FormulaR1C1 = "=tb_DATA[[#This Row],[Service/Log Formula]]"
    End With
End Sub

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