【问题标题】:Excel VBA: Using Cell Colors For CalculationExcel VBA:使用单元格颜色进行计算
【发布时间】:2014-07-10 22:33:32
【问题描述】:

我刚刚开始学习如何使用 VBA,但我遇到了困难。我所拥有的是一个 Excel 表,其中充满了库存行,该行的所有列上都有红色单元格,我想打印其中存在差异的地方。

换句话说,如果单元格颜色为红色,我最终希望它采用该列的第一个单元格(标题)并像字符串连接一样附加值。我希望它对该行中的所有红色单元格都这样做。例如,如果一行中的红色单元格位于重置和时间列中,我希望该行的最后一列显示“重置:20,时间:30”。

所以我开始的只是尝试逐个单元格和逐行进行,以便我可以计算红色单元格的数量并尝试将它们放在每行的末尾。搞砸了,我注意到我下面的代码会自动将 x 放在相邻的单元格中,因为它会增加,而不是像我预期的那样保持一个单元格。我目前也有 cell(row, 60) 因为列总是相同的,但它不喜欢我使用变量 row。

    Sub CellColorRed()
'
' CellColorRed Macro
' Take headers if color is red
'
' Keyboard Shortcut: Ctrl+n
'
    Dim rng As Range, cell As Range, row As Range, x As Integer
    Set rng = Range("F2:BG9")
    For Each row In rng.Rows
        For Each cell In rng.Cells
        x = 0
            If cell.Interior.ColorIndex = 3 Then
                x = x + 1
            End If
            cell(row, 60) = x
        Next cell
    Next row
End Sub

【问题讨论】:

    标签: excel vba


    【解决方案1】:
    Sub GetRedCells()
    
        Dim rng As Range, cell As Range, row As Range, x As Integer
        Dim msg as String, sep as string
    
        Set rng = Range("F2:BG9")
        For Each row In rng.Rows
            msg=""
            sep=""
    
            For Each cell In row.Cells
                If cell.Interior.ColorIndex = 3 Then
                    msg = msg & sep & Cells(1, cell.Column).Value & _
                          ": " & cell.Value 
                    sep = ", "
                End If
            Next cell
    
            row.cells(60) = msg
    
        Next row
    
    End Sub
    

    【讨论】:

    • 谢谢。效果很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多