Srinivas在A列和B列中都有数据。他需要对B列中的值求和,A列中相应单元格的单元格格式为此黄色。例如,如果单元格A17中的格式为黄色,则单元格B17中的值应包括在总和中。

Internet上有许多可用的宏(包括_ExcelTips_),您可以根据单元格的颜色或其他格式进行条件求和。但是,此需求有所不同,因为它不是所讨论的单元格的颜色,而是单元格的颜色在左侧的一列中。仍然可以使用宏完成此操作,如下所示:

Function SumNextYellow(ByVal r As Range)

Dim c As Range     Dim a As Double

For Each c In r         If c.Offset(0, -1).Interior.ColorIndex = 6 Then 'Yellow             a = a + c.Value         End If     Next c     SumNextYellow = a End Function

该函数可以在工作表公式中使用,并接受范围引用作为参数。然后,它将逐步遍历该范围内的每个单元格,如果左侧的单元格是黄色,则该值包括在总和中。 (您应注意,宏中使用的ColorIndex应该与您的Excel版本一起测试,以确保它适用;在不同版本中可能有所不同。)

下面的清单中显示了一个更强大的示例。此函数接受一个或多个单元格范围,以及一个表示要使用的格式示例的参数。

Function ColorConditionSum(cSample As Excel.Range, rng As Excel.Range)

' This Function returns sum of values in rng.Columns(2) if ' corresponding cell in rng.Columns(1) is colored with sample ' color (cSample cell)



' Arguments: cSample = cell colored by sample color '            rng = cell range to be processed (2 columns)



Dim rngCol2 As Excel.Range     Dim rngConstants As Excel.Range     Dim rngFormulas As Excel.Range     Dim lColorIndex As Long     Dim MySum As Double     Dim area As Excel.Range     Dim c As Excel.Range

ColorConditionSum = False     If Not TypeOf cSample Is Excel.Range Then Exit Function '>>>     lColorIndex = cSample.Interior.ColorIndex

MySum = 0     Set rngCol2 = Nothing     If TypeOf rng Is Excel.Range Then         If rng.Columns.Count < 2 Then Exit Function '>>>         On Error Resume Next         For Each area In rng.Areas             If rngCol2 Is Nothing Then                 Set rngCol2 = area.Columns(2).SpecialCells(xlCellTypeConstants, 1)

If rngCol2 Is Nothing Then                     Set rngCol2 = area.Columns(2).SpecialCells(xlCellTypeFormulas, 1)

Else                     Set rngCol2 = Application.Union( _                         rngCol2, area.Columns(2).SpecialCells(xlCellTypeFormulas, 1))

End If             Else                 Set rngCol2 = Application.Union( _                     rngCol2, area.Columns(2).SpecialCells(xlCellTypeConstants, 1))

Set rngCol2 = Application.Union( _                     rngCol2, area.Columns(2).SpecialCells(xlCellTypeFormulas, 1))

End If         Next area

For Each area In rngCol2.Areas             For Each c In area.Cells                 With c.Offset(0, -1)

If .Interior.ColorIndex = lColorIndex Then                         MySum = MySum + c.Value                     End If                 End With             Next c         Next area     End If

ColorConditionSum = MySum End Function

您可以通过以下方式在工作表中使用此功能:

=ColorConditionSum(A10, A12:B22)

在这种情况下,是具有想要匹配的内部颜色的单元格,而A12:B22是要评估的单元格范围。从范围中的第二列中提取值,并在第一列中的单元格上检查格式。

注意:

如果您想知道如何使用此页面(或_ExcelTips_网站上的任何其他页面)中描述的宏,我准备了一个特殊页面,其中包含有用的信息。

_ExcelTips_是您进行经济高效的Microsoft Excel培训的来源。

本技巧(3298)适用于Microsoft Excel 97、2000、2002和2003。可以在以下功能区中为Excel的功能区界面(Excel 2007及更高版本)找到本技巧的版本: