条件累积和宏

时间:2014-01-16 20:51:27

标签: excel vba excel-vba

您好我已经被困在我的第一个子程序上了一段时间并尝试研究我的问题,但对VBA来说还是比较新的,所以几乎找不到具体的运气。我有一个相当大的电子表格(56090行),其中包含一系列具有唯一名称的项目的每日数据点。项目名称位于D列,我需要的数据位于F和H列。我正在尝试为列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

2 个答案:

答案 0 :(得分:1)

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

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

  • 但如果您更喜欢VBA,请尝试更改代码:

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

    cel= 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
    

答案 1 :(得分:0)

我尝试过这样的事情:

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)

我必须为我声明的所有变量编写上述内容。

相关问题