1

在此处输入图像描述我正在编写一个循环遍历 Excel 数据的宏,该数据按 A 列排序,如果 coulmn 的值与上面的值不同,则插入一个空白行。这会将我的数据按 A 列分组。

然后我想对分离组的 d 列的值求和。我的大部分代码都在下面工作,但是我遇到了问题的 startCell 变量。我知道我想做什么,但无法正确理解逻辑,有人可以帮助总结这些个人群体。

非常感谢

Sub PutARowInWithFormula()
  Range("A3").Select

  Dim startCell As Integer
  Dim endCell As Integer

  startCell = 3
  endCell = 0

  Do Until ActiveCell.Value = ""
    If ActiveCell.Value = ActiveCell.Offset(-1, 0).Value Then
      ActiveCell.Offset(1, 0).Select
    Else
      ' I need the bottom code to execute only once in the loop
      ' startCell = ActiveCell.Row
      ActiveCell.EntireRow.Insert

      ' move to column d
      ActiveCell.Offset(0, 3).Select

      endCell = ActiveCell.Row - 1
      ActiveCell.Formula = "=Sum(d" & startCell & ":d" & endCell & ")"

      ' move back to column a
      ActiveCell.Offset(0, -3).Select

      'move 2 rows down
      ActiveCell.Offset(3, 0).Select
    End If
  Loop
End Sub
4

1 回答 1

3

我也很想知道,为什么您不使用数据透视表或仅使用工作表函数创建它,这也是可能的。此外,我不太喜欢这种选择尝试,但它是你的方式,我尊重这一点。当使用它们可能是一个好主意时,它甚至似乎是一个很好的例子。因为现在,我能想到的任何其他方式,在 VBA 中执行此操作,似乎都更复杂。

因此,这是您的代码的修复:

Sub PutARowInWithFormula()
  Range("A2").Select

  Do Until ActiveCell.Value = ""
    If ActiveCell.Value = ActiveCell.Offset(-1, 0).Value Then
      ActiveCell.Offset(1, 0).Select
    Else
      ActiveCell.EntireRow.Insert

      'you can use the offset directly
      'by using an improved formula, you do not need to know start and end row.
      ActiveCell.Offset(0, 3).Formula = _
        "=SUMIF(A:A,OFFSET(INDIRECT(""A""&ROW()),-1,0),D:D)"

      ' move back to column a and move 2 rows down
      ActiveCell.Offset(2, 0).Select
    End If
  Loop
End Sub

编辑

好的,找到了一种更简单的方法来做几乎同样的事情:

Public Sub demo()
  UsedRange.Subtotal GroupBy:=1, Function:=xlSum, TotalList:=4
End Sub

此功能也可通过功能区菜单 -> 数据 -> sumsum 使用

为了避免错误消息,您只需要为您的数据设置一个标题行,例如:

日期 | 姓名 | 柜台 | 价值

于 2012-11-15T14:02:20.350 回答