VBA:仅填充背景填充单元格的inputSUM公式

我对VBA相当陌生,我试图写一段代码,将一个总和公式插入到蓝色单元格中,并总结到下一个蓝色单元格(见附件)。 我需要这样做的原因是因为这将是一个用户谁将插入一个文本文件到这个电子表格的模板,所以我想它格式的单元格,并添加公式,所以如果他们决定添加一个新的行,它会自动重新计算总量。 任何帮助将不胜感激!!! 让我知道如果你需要更多的细节!

F1

不太确定数据的其余部分是如何看起来过去的,但是像这样的东西应该可以工作。 我试图尽可能彻底地发表评论,以帮助解释这是如何做的,所以你可以了解更多关于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 

我build议查看帮助中心( https://stackoverflow.com/help )并阅读其中的一些主题,发布类似这样的问题,但不会显示您尝试的内容通常会很快closures。