2017-09-11 447 views
0

我有下面的代碼找到第一個空白單元格並在最後一個空白單元格下面的數據求和。Excel VBA - 如何找到空白單元格和從活動單元格到空白單元格的總和

Dim r As Range 
Dim lngRowStart As Long 
If Range("A1").Formula <> "" Then 
    lngRowStart = 1 
Else 
    lngRowStart = Range("A1").End(xlDown).Row 
End If 
    Set r = Cells(lngRowStart, 1).End(xlDown).Offset(1, 0) 
If Left(r.Offset(-1, 0).Formula, 1) <> "=" Then 
     r.FormulaR1C1 = "=Subtotal(9,R[-" & r.Row - lngRowStart & "]C:R[-1]C)" 
End If 

但這假定數據是在列A和用於所述第一組連續的數據的,如何修改它的任何有源單元來總結以上連續數據?

例如:

2 

4 

3 

Blank (SUM ABOVE=9) 

1 

3 

2 

Blank (SUM ABOVE=6) 

回答

0

您可以使用下面的UDF(代碼的註釋中說明):

Function SumContinRange(CurCell As Range) As Double  
    Dim RngStart As Range, SumRng As Range   

    If CurCell <> "" Then 
     ' find the first empty cell using the Find function 
     Set RngStart = Columns(CurCell.Column).Find(what:="", After:=CurCell, LookIn:=xlValues) 
    Else 
     ' find the first empty cell using the Find function 
     Set RngStart = Columns(CurCell.Column).Find(what:="", After:=CurCell, LookIn:=xlValues, SearchDirection:=xlPrevious) 
    End If 

    ' set the Sum Range 
    Set SumRng = Range(RngStart.Offset(-1, 0), RngStart.Offset(-1, 0).End(xlUp)) 

    SumContinRange = WorksheetFunction.Sum(SumRng) ' return this value 
End Function 

然後,使用下面的Sub經過ActiveCell測試:

Sub TestFunc() 

If ActiveCell.Value <> "" Then 
    ActiveCell.End(xlDown).Offset(1) = SumContinRange(ActiveCell) 
Else 
    ActiveCell = SumContinRange(ActiveCell) 
End If 

End Sub 
相關問題