SUM范围取决于VBA的值

时间:2019-02-25 13:46:53

标签: excel vba sum

我正在尝试对VBA执行以下操作。想象一下,我有一些数据,如下所示:

enter image description here

我希望最终结果是“ BEGINDATA”和“ ENDDATA”之间的每个数据的总和。看起来像这样:

enter image description here

我的目标是获取绿色数据并将其写入“ ENDDATA”旁边

有什么想法或建议吗?

非常感谢您!

2 个答案:

答案 0 :(得分:1)

尝试:

Option Explicit

Sub test()

    Dim Lastrow As Long, BeginData As Long, EndData As Long, i As Long

    With ThisWorkbook.Worksheets("Sheet1")

        Lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row

        For i = 1 To Lastrow

            If .Range("A" & i).Value = "BEGINDATA" Then
                BeginData = i
            ElseIf .Range("A" & i).Value = "ENDDATA" Then
                EndData = i
            End If

            If EndData > BeginData Then
                .Range("B" & i).Value = Application.Sum(.Range("B" & BeginData + 1 & ":B" & EndData - 1))
            End If

        Next i

    End With

End Sub

另一个版本:

Option Explicit

Sub test()

    Dim Lastrow As Long, BeginData As Long, EndData As Long, i As Long

    With ThisWorkbook.Worksheets("Sheet1")

        Lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row

        For i = 1 To Lastrow

            If .Range("A" & i).Value = "BEGINDATA" Then
                BeginData = i
            ElseIf .Range("A" & i).Value = "ENDDATA" Then
                EndData = i
            End If

            If EndData > BeginData Then
                With .Range("B" & i)
                    .Value = Application.Sum(Sheet1.Range("B" & BeginData + 1 & ":B" & EndData - 1))
                    .Interior.Color = vbGreen
                End With
            End If

        Next i

    End With

End Sub

答案 1 :(得分:0)

您还可以使用Option Explicit Sub Demo() Dim BeginData As Range, EndData As Range Dim FirstBeginAddress As String ' Update with your range With Sheet1.Columns(1) Set BeginData = .Find(what:="BEGINDATA", after:=.Cells(.Cells.Count), LookIn:=xlValues, lookat:=xlWhole) If Not BeginData Is Nothing Then FirstBeginAddress = BeginData.Address Set EndData = .Find("ENDDATA", after:=BeginData) Do Debug.Print "BeginAddress", BeginData.Address If Not EndData Is Nothing And EndData.Row > BeginData.Row Then Debug.Print "EndAddress", EndData.Address '' For Formula EndData.Offset(0, 1).Formula = "=SUM(" & Range(BeginData.Offset(1, 1), EndData.Offset(-1, 1)).Address & ")" '' For value 'EndData.Offset(0, 1).Value2 = Application.Sum(Range(BeginData.Offset(1, 1), EndData.Offset(-1, 1))) Set EndData = .Find("ENDDATA", after:=EndData) Else Err.Raise 998, "Demo", "Unable to find Data Footer" End If Set BeginData = .Find("BEGINDATA", after:=BeginData) Loop Until BeginData Is Nothing Or BeginData.Address = FirstBeginAddress Else Err.Raise 999, "Demo", "Unable to find Data Header" End If End With End Sub 来实现此目的,这比循环要快

offset