VBA:跳过范围内的单元格

gaf*_*fcz 4 excel vba excel-vba

我正在尝试在C列填写公式,如下所示:

LastRow = Range("A65536").End(xlUp).Row
Range(Cells(1, 3), Cells(LastRow, 3)).Formula = "=A1*B1"
Run Code Online (Sandbox Code Playgroud)

它工作正常.但是有可能跳过C列中的那些单元格,其值例如> 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
Run Code Online (Sandbox Code Playgroud)

Sid*_*out 6

为此,您需要对数据的外观稍作改动.例如,您需要将"标题"添加到第一行.我们这样做的原因是因为我们会使用AutoFilter

假设您的数据看起来像这样

在此输入图像描述

现在使用此代码

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
Run Code Online (Sandbox Code Playgroud)

产量

在此输入图像描述