Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA: Skip cells in range

Tags:

excel

vba

I'm trying to fill formulas in column C like this:

LastRow = Range("A65536").End(xlUp).Row
Range(Cells(1, 3), Cells(LastRow, 3)).Formula = "=A1*B1"

And it works fine. But is it possible to skip those cells in column C, which value is for example > 0 ?

A B C -> A B C
3 2 0    3 2 6
3 4 0    3 4 12
5 6 5    5 6 5  <- this value is not updated
like image 915
gaffcz Avatar asked Mar 18 '23 13:03

gaffcz


1 Answers

For this you will have to do a slight change to how your data looks like. For example, you need to add "Header" to the first row. The reason we would do that is because we would be using AutoFilter

Let's say your data looks like this

enter image description here

Now use this code

Sub Sample()
    Dim ws As Worksheet
    Dim copyFrom As Range
    Dim lRow As Long

    '~~> Change this to the relevant sheet
    Set ws = ThisWorkbook.Worksheets("Sheet1")

    With ws

        '~~> Remove any filters
        .AutoFilterMode = False

        '~~> Get lastrow in column c
        lRow = .Range("C" & .Rows.Count).End(xlUp).Row

        '~~> Filter the col C to get values which have 0
        With .Range("C1:C" & lRow)
            .AutoFilter Field:=1, Criteria1:="=0"

            Set copyFrom = .Offset(1, 0).SpecialCells(xlCellTypeVisible)

            '~~> Assign the formula to all the cells in one go
            If Not copyFrom Is Nothing Then _
            copyFrom.Formula = "=A" & copyFrom.Row & "*B" & copyFrom.Row
        End With

        '~~> Remove any filters
        .AutoFilterMode = False
    End With
End Sub

Output

enter image description here

like image 106
Siddharth Rout Avatar answered Mar 28 '23 15:03

Siddharth Rout