VBA:仅用于背景填充单元格的输入和公式

VBA:仅用于背景填充单元格的输入和公式,vba,excel,Vba,Excel,我是VBA的新手,我正在尝试编写一段代码,在蓝色单元格中插入一个求和公式,然后求和,直到下一个蓝色单元格见附件。我之所以需要这样做,是因为这将是一个模板,供将文本文件插入此电子表格的用户使用,所以我希望它能够格式化单元格并添加公式,这样,如果他们决定添加新行,它将自动重新计算总数。任何帮助都将不胜感激!!!如果你需要更多细节,请告诉我 我不确定你的其他数据是如何通过屏幕截图的,但类似的东西应该可以工作。我试图尽可能全面地进行评论,以帮助解释它是如何完成的,这样您就可以了解更多有关VBA工作原理的

我是VBA的新手,我正在尝试编写一段代码,在蓝色单元格中插入一个求和公式,然后求和,直到下一个蓝色单元格见附件。我之所以需要这样做,是因为这将是一个模板,供将文本文件插入此电子表格的用户使用,所以我希望它能够格式化单元格并添加公式,这样,如果他们决定添加新行,它将自动重新计算总数。任何帮助都将不胜感激!!!如果你需要更多细节,请告诉我


我不确定你的其他数据是如何通过屏幕截图的,但类似的东西应该可以工作。我试图尽可能全面地进行评论,以帮助解释它是如何完成的,这样您就可以了解更多有关VBA工作原理的信息

Sub SumBetweenBlues()

'declare your variables
Dim ws As Worksheet
Dim x As Long, y As Long, endRow As Long, startSum As Long, endSum As Long, xBlue as Long
Dim colL As String

'set the worksheet to work with (this can be changed if necessary)
Set ws = ActiveWorkbook.ActiveSheet

'set the color of blue to check for
xBlue = RGB(201, 234, 236)

'column where the sums will be put (C)
Const sumCol As Integer = 3

'first row
Const startRow As Integer = 2

'turns the column number into a letter for the formula
colL = colLetter(sumCol)

'determines the last used row and goes a bit past it since blues may/may not be blank themselves
endRow = ws.Cells(ws.Rows.Count, sumCol).End(xlUp).Row + 50

'loop through all the cells in the sum column
For x = startRow To endRow

    'checks if the cell is blue
    If ws.Cells(x, sumCol).Interior.Color = xBlue Then

        'set the start of the sum range to the cell after the blue cell
        startSum = x + 1

        'find the end of the sum range
        For y = startSum + 1 To endRow

            'checks if the cell is also blue
            If ws.Cells(y, sumCol).Interior.Color = xBlue Then

                'sets the end of the sum range to the cell before the blue cell
                endSum = y - 1
                Exit For

            End If
        Next y

        'so long as an endsum area was found, set the formula in the blue cell
        If endSum <> 0 Then
            ws.Cells(x, sumCol).Formula = "=SUM(" & colL & startSum & ":" & colL & endSum & ")"
        End If

        'skip all the non-blue cells inbetween
        x = y - 1

        'reset the start/end of the sum area
        startSum = 0
        endSum = 0

    End If

Next x

End Sub

'---------------------------------------------------------------------------

Function colLetter(intCol As Integer) As String
'this function turns column numbers into letters
Dim vArr: vArr = Split(Cells(1, intCol).Address(True, False), "$"): colLetter = vArr(0)
End Function

我建议查看帮助中心并阅读其中的一些主题,因为在没有显示您尝试过的内容的情况下发布这样的问题通常会很快关闭。

请阅读。谢谢J.Fox!我试试看。我本来打算发布我所拥有的东西,但A不多,B我不知道如何真正找到彩色细胞开始=。我会让你知道我带了什么回来!嗨,JFox,出于某种原因,我得到了RGB的“需要常量表达式”。我需要将其设置为常量吗?您使用的是什么版本的Excel?我只需要将constxblue=RGB201,234,236在一行上更改为dimxblue=RGB201,234,236,在下一行上更改xBlue=RGB201,234,236,我更改了上面的答案以反映这一变化。先生,您太棒了。成功了!!非常感谢。