【问题标题】:VBA: Skip cells in rangeVBA:跳过范围内的单元格
【发布时间】:2014-09-04 08:27:24
【问题描述】:

我正在尝试像这样在 C 列中填充公式:

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

而且效果很好。但是是否可以跳过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

【问题讨论】:

  • @Mehow:有可能:)
  • @SiddharthRout ++ 回答你的问题,我收回我的最后评论:)

标签: vba excel


【解决方案1】:

为此,您必须对数据的外观进行轻微更改。例如,您需要将“标题”添加到第一行。我们这样做的原因是我们将使用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

输出

【讨论】:

  • 非常感谢! :-)
【解决方案2】:

一种通过循环实现的方法:

    Sub test()

            Dim rngTest As Range
            Dim rngCell As Range

            LastRow = Range("A65536").End(xlUp).Row
            Set rngTest = Range(Cells(1, 3), Cells(LastRow, 3))
            Application.Calculation = xlCalculationManual
            For Each rngCell In rngTest.Cells
                If Not rngCell <> "" Then
                    rngCell.Formula = "=" & rngCell.Offset(, -2).Address & "*" & rngCell.Offset(, -1).Address
                End If
            Next
            Application.Calculation = xlCalculationAutomatic
    End Sub

【讨论】:

  • 谢谢,您的解决方案对我来说更容易理解。效果很好!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-11
  • 2015-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多