如何编辑我的总和公式来select单元格的dynamic范围?

我logging了一个macros,确保使用相对引用被选中,但运行macros时,总和函数总是select总共出现的单元格上方的8个单元格,即使我使用Ctrl + Shift + 向上箭头键select了所有非直接在上面的细胞 如何输入公式

ActiveCell.FormulaR1C1 = "=SUM(R[-8]C:R[-1]C)

我看了以下类似于我想要实现的内容,但是我的内容是相反的,并且不知道如何修改我的代码,它将汇总列上移动的每个单元格,直到达到空白单元格为止。

  • 在范围内select单元格,直到行为空

  • select单元格的dynamic范围

目标是能够在工作表中的不同位置input小计,在这些小计中他们总计范围内的单元格数量不同。

这是整个macros观看起来像是否有助于看到上下文:

 Sub InsertTotal() ' ' InsertTotal Macro ' Insert blank rows, bold line and total amount ' ' Keyboard Shortcut: Ctrl+y ' ActiveCell.Rows("1:2").EntireRow.Select Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove ActiveCell.Offset(0, 7).Range("A1").Select Selection.Font.Bold = True ActiveCell.FormulaR1C1 = "=SUM(R[-8]C:R[-1]C)" ActiveCell.Offset(-1, -7).Range("A1").Select Range(Selection, Selection.End(xlToRight)).Select Selection.Borders(xlDiagonalDown).LineStyle = xlNone Selection.Borders(xlDiagonalUp).LineStyle = xlNone Selection.Borders(xlEdgeLeft).LineStyle = xlNone Selection.Borders(xlEdgeTop).LineStyle = xlNone With Selection.Borders(xlEdgeBottom) .LineStyle = xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlMedium End With Selection.Borders(xlEdgeRight).LineStyle = xlNone Selection.Borders(xlInsideVertical).LineStyle = xlNone Selection.Borders(xlInsideHorizontal).LineStyle = xlNone ActiveCell.Select End Sub 

任何意见或build议将是一个巨大的帮助

 Public Function sumAbove(ByVal CellSelected As Range) As Double Dim FirstSelected As Range Dim TopMostNonBlankCell As Range Set FirstSelected = CellSelected.Cells(1) 'if user inputs more than one cell, we use only the first If FirstSelected.Offset(-1).Value2 = vbNullString Then 'we check, if the value above FirstSelected is blank Set TopMostNonBlankCell = FirstSelected Else 'If it is not blank, we use CTRL+SHIFT+UP Set TopMostNonBlankCell = FirstSelected.End(xlUp) End If 'Some error handling should be put above, to handle if the sumAbove is used in first row. sumAbove = WorksheetFunction.Sum(Range(TopMostNonBlankCell, CellSelected).Value2) End Function 

EDIT1

为了将其纳入您的代码,请尝试使用这个:
ActiveCell.FormulaR1C1 = "=SUM(" & ActiveCell.Offset(-1).Address(ReferenceStyle:=xlR1C1) & ":" & ActiveCell.Offset(-1).End(xlUp).Address(ReferenceStyle:=xlR1C1) & ")"

解释:

  • 为了避免循环引用,我们需要用-1行偏移活动单元格。
  • 您可以简化代码以使用默认的A1引用符号,如下所示: ActiveCell.Formula = "=SUM(" & ActiveCell.Offset(-1).Address & ":" & ActiveCell.Offset(-1).End(xlUp).Address & ")" 。 结果是一样的。
  • 你将需要一些exception处理(请参阅上面的函数)。
  • 为了使代码更有效率和可读性,一些范围variables,如Set ActiveCellMinusRow = ActiveCell.Offset(-1) ,并在我提出的代码中使用它。

这是我使用的解决scheme,因为它覆盖了我可以在数据集中使用的所有选项。

 If ActiveCell.Offset(-2) = "" Then ActiveCell.Formula = "=SUM(" & ActiveCell.Offset(-1).Address & ":" & ActiveCell.Offset(-1).Address & ")" Else ActiveCell.Formula = "=SUM(" & ActiveCell.Offset(-1).Address & ":" & ActiveCell.Offset(-1).End(xlUp).Address & ")" End If