【问题标题】:How to provide range in Macro in Excel in below formula如何在下面的公式中在 Excel 中的宏中提供范围
【发布时间】:2016-08-16 21:38:12
【问题描述】:

我必须创建一个公式,其中存在 3 列 ABC,它的值直到说序列号 5。所以现在必须检查单元格中的值是否说 C1 为空白然后单元格B1 将是A1/Count(C)

我可以对单个单元格执行此操作,但如何使用下面的公式计算A1:A5B1:B5C1:C5 的范围

Sub CheckCnt()

Range("C6") = WorksheetFunction.CountA(Range("C1:C5"))

If Range("C1") = "" Then
    Range("B1") = WorksheetFunction.Round(Range("A1") / Range("C6"), 2)
Else
Range("B1") = 0

End If
End Sub

【问题讨论】:

    标签: excel vbscript macros vba


    【解决方案1】:

    将其放入 FOR 循环应该可以工作。 请参阅下面的修订代码。

    Sub CheckCnt()
        Dim rw as Integer
    
    Range("C6").Value = WorksheetFunction.CountA(Range("C1:C5"))
    For rw = 1 to 5
        If Range("C" & rw).Value = "" Then
            Range("B" & rw).Value = WorksheetFunction.Round(Range("A" & rw).Value / Range("C6").Value, 2)
        Else
            Range("B" & rw).Value = 0
        End If
    Next rw
    
    End Sub
    

    让我知道这是否有效。非常感谢!

    【讨论】:

    • 按预期工作..谢谢!
    • 很高兴听到这个消息。随意对答案进行投票,以便可以关闭这个问题。您的支持将使我能够发布 cmets 并在未来帮助更多人。
    • 我试过但没有这样做,因为这样做至少需要 15 个声望,而我的声望是 1。
    • 哦,我什至没有意识到这一点。非常感谢你的尝试。如果您有任何其他问题,请告诉我。
    【解决方案2】:

    我不确定要插入什么公式,所以我将 ROUND 公式放在了 B1:B5 范围内。

    B1 将是:=ROUND($A1/$C$6,2)
    B2 将是:=ROUND($A2/$C$6,2)
    等等……

    此代码使用 R1C1 表示法:

    Sub CheckCnt()
    
        'Be specific about which sheet you want the result in (otherwise it will appear in the selected sheet).
        With ThisWorkbook.Worksheets("Sheet1")
            With .Range("B1:B5")
                .FormulaR1C1 = "=Round(RC1/R6C3,2)" 'Use a formula with R1C1 notation.
                .Value = .Value 'Replace the formula with the result of the formula.
            End With
        End With
    
    End Sub
    

    RC1 表示这一行第 1 列。R6C3 表示第 6 行第 3 列。
    http://www.numeritas.co.uk/2013/09/the-%E2%80%98dark-art%E2%80%99-of-r1c1-notation/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-24
      • 2012-06-04
      • 1970-01-01
      • 2020-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多