如何对两个范围地址之间的值求和

时间:2019-10-24 20:31:04

标签: excel vba

我有一个表,在第20行的标题处带有单词“ Circuit” 1,2,3..etc。根据用户的输入,每个“ Circuit”标题下面都有可变的列数。

我正在尝试汇总此表的第38行,直到下一个“ Circuito” +数字参数开始。我能够检索要汇总的每个范围的起点和终点。但是,我找不到求和值的方法。

For j = 1 To NumCirc 'NumCirc is the number of circuits
    Set rgfound = Range("B20:BZ20").Find("Circuit " & j)
    a = rgfound.Offset(18, 0).Address 'this is the first value
    b = rgfound.End(xlToRight).Offset(18, -1).Address 'this is the last value
Next j

自从我找到起点和终点以来,我希望总结它们之间的所有内容。 Worksheet.sum(a,b)仅对“ a”和“ b”求和,但不求和该范围内的所有值。

任何人都可以给我提供有关如何执行此操作的见解吗?谢谢!

1 个答案:

答案 0 :(得分:0)

您可以将Range内的Range括起来,不需要地址。

ab更改为RangeSet

Dim a as Range
Set a = rgfound.Offset(18, 0)

Dim b as Range
Set b = rgfound.End(xlToRight).Offset(18, -1)

然后

... WorksheetFunction.Sum(Range(a, b))

其他说明

  1. 您应该测试是否找到范围:

    Set rgfound = Range("B20:BZ20").Find("Circuit " & j)
    
    If Not rgfound Is Nothing Then
        Set a = ...
        Set b = ...
        ...     
    End If
    
  2. 最佳实践是指定Range在哪个工作表上,除非您特别想使用ActiveSheet-当前是隐含的。