Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

excel - Counting upward in column until blank?

I have a column, which will contain a few rows of data, and then a blank cell.

I need a way to count the rows upwards in a column until a blank cell and sum the number using VBA. Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'm not 100% sure what you are asking. You say "sum the number" but do not specify if the number you want to sum is the number of rows counted or if you want to sum the value of the cells found.

-Edit-

Give this a try: This will start at the bottom row and count upward until it finds a blank cell Once a blank cell is found it will sum the cells between the last blank cell and the current blank cell.

-Edit2-

Added insert to the row under column headers so the first row also gets summed.

Sub CountUp()
    Dim TotalRows As Long
    Dim TotalCols As Long
    Dim Col As Long
    Dim i As Long
    Dim n As Long

    Rows(2).Insert Shift:=xlDown
    TotalRows = ActiveSheet.UsedRange.Rows.Count
    TotalCols = ActiveSheet.UsedRange.Columns.Count
    'Assumes Data you want to sum is in the first column
    Col = 1

    Cells(TotalRows, Col).Select
    For i = TotalRows To 1 Step -1
        If Cells(i, Col).Value <> "" Then
            n = n + 1
        Else
            Cells(i, Col).Formula = "=SUM(" & Cells(i + 1, Col).Address(False, False) & ":" & Cells(i + n, Col).Address(False, False) & ")"
            n = 0
        End If
    Next
End Sub

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...