2016-05-14 4 views
-4
LastRow = Cells(Rows.Count, 12).End(xlUp).Row 
Cells(LastRow + 1, 12).Formula = "=sumcellsbycolor(K1:K" & LastRow & ",(colorindex=6))" 

(colorindex = 6)の代わりに、私たちは必要な色のセルを選択する必要があります。しかし、私はrefを与えるために固定された細胞を持っていないので。VBAコード - Sumbycellscolor

は、どのように私はあなたがこのプログラムコードを試すことができ、上記の式

答えて

0

にこの色のインデックスを使用することができます。あなたは"L1"の色で合計の結果を得ます。色の選択はRange(M1:M3)です。コードで行番号の表示を変更する必要があります。コードの後の画像はサンプルデータを示しています。 HTH

ここ
Sub SumByColorV() 

    Dim ws As Worksheet 
    Dim lastRow As Long 
    Dim result As Long 
    Dim cSum As Long 
    Dim ColIndex As Integer 
    Dim CellColor As Range 
    Dim rRange As Range 
    Set CellColor = ActiveSheet.Cells(1, 13) 'Vary row no 1 or 2 or 3 of column 13 (M) as per yr requirement 
    lastRow = ActiveSheet.Cells(Rows.Count, "K").End(xlUp).Row 
    Set rRange = ActiveSheet.Range(Cells(1, 11), Cells(lastRow, 11)) 
    ColIndex = CellColor.Interior.ColorIndex 

    For Each cl In rRange 
     If cl.Interior.ColorIndex = ColIndex Then 
     cSum = WorksheetFunction.Sum(cl, cSum) 
     End If 
    Next cl 
    result = cSum 
    ActiveSheet.Cells(1, 12).Value = result 
End Sub 

Sample data with result

0

は2つの引数を渡すことができる機能、セルの範囲及びカラーインデックス、色のための標準的な名前、または1つの細胞のいずれかとすることができる変異体であります範囲。それはその引数の範囲を渡された場合、それは範囲のカラーインデックスに対して合計:

Function IndexFromName(ByVal colorName As String) As Long: 
    Dim s As String, i As Long 
    s = LCase(colorName) 
    Select Case s 
     Case "black": i = 1 
     Case "white": i = 2 
     Case "red": i = 3 
     Case "green": i = 4 
     Case "blue": i = 5 
     Case "yellow": i = 6 
     Case "magenta": i = 7 
     Case "cyan": i = 8 
     Case Else: i = -4142 'color automatic -- perhaps should return an error 
    End Select 
    IndexFromName = i 
End Function 

Function SumIfColor(R As Range, color As Variant) As Double 
    'summ cells with a given color index 
    'which may differ from displayed color 
    'if conditional formatting is in use! 
    Dim i As Long, ci As Long, s As Double, c As Range 

    If TypeName(color) = "Range" Then 
     ci = color.Interior.ColorIndex 
    ElseIf TypeName(color) = "String" Then 
     ci = IndexFromName(color) 
    Else 
     ci = color 
    End If 
    For Each c In R.Cells 
     If c.Interior.ColorIndex = ci Then s = s + c.Value 
    Next c 
    SumIfColor = s 

End Function 

これは、スプレッドシートに直接使用することができる:上記画像Iにおいて

enter image description here

セルA14に式=SumIfColor($A$1:$H$10,A13)を入力し、nxtの2つの列にコピーしました。

もちろん、IndexFromNameを展開することもできます。私はvbYellowのような名前付き定数に対応する8色しか実装していませんでした。たとえば、標準のExcelカラーパレットで他の色の標準HTML色名を決定することができます。

Excelの色は、セルのカラーインデックスよりもかなり複雑になっています。表示された色はもはやパレットに限定されず、条件付き書式化は一定の複雑な要因である。唯一の有効なユースケースは、表示される色のみが、ユーザーがカラーパレットを使用して明示的に選択した色である場合です。