有条件的累积和macros

你好我一直在我的第一个子程序已经停留了一段时间,并试图研究我的问题,但对VBA是相当新的,所以有运气find任何具体的东西。 我有一个相当大的电子表格(56090行),这是充满每日数据点的一堆具有唯一名称的项目。 项目名称位于列D和我需要的数据位于列F和H.我试图创build一个累积总和为K列中的每一天,重置时达到一个新的项目名称(通过检查当前行项目名称与上一行项目名称)。 代码我似乎做的伎俩,但停止行22510行(没有错误,只是在这一行之后的总和值是错误的)。

Sub cum(ByVal DataPoints As Long) Application.ScreenUpdating = False Dim index As Long Dim runningCum As Long runningCum = 0 For index = 3 To DataPoints 'Set cell to Cum Oil column at index row cel = Cells(index, "K") 'If the well name in previous row is equal to well name in index row, add oil values to runningCum If Cells(index - 1, "D") = Cells(index, "D") Then runningCum = runningCum + Cells(index, "F") + Cells(index, "H") 'Otherwise, reset runningCum Else runningCum = 0 End If 'Set the Cum Oil cell value to the runningCum cel = runningCum Next Application.ScreenUpdating = True End Sub 

  • 你可以在K3使用非常简单的公式,并将其拉伸:

    =IF(D2=D3,K2+F3+H3,0)

  • 但是如果你喜欢VBA,试着改变你的代码:

    cel = Cells(index, "K") to Set cel = Cells(index, "K")

    cel= runningCum cel.Value = runningCumcel.Value = runningCum

  • 或者可以使用下面的简单代码(它使用公式计算值,然后删除公式并仅保留值):

     Sub cum(ByVal DataPoints As Long) With Range("K3:K" & DataPoints) .Formula = "=IF(D2=D3,K2+F3+H3,0)" .Calculate .Value = .Value End With End Sub 

我试过这样的事情:

 Dim a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, aa, ab, ac As String If Trim(range("A1").Value) <> "name" Then a = " Header for Column A is incorrect " If Trim(range("B1").Value) <> "type" Then a = " Header for Column B is incorrect " MsgBox (" The following error(s) have occured " & vbCrLf & vbCrLf & a & b) 

我必须为我已经声明的所有variables写上述内容。