簡體   English   中英

使用excel宏添加連續數字並粘貼到空白單元格中

[英]Add Consecutive numbers and paste in blank cell using excel macro

我有一組要添加並放置在下一個空白單元格中的數字。 在示例中A1A11必須在A12求和。 下一組也一樣。 我想要一個宏來執行此操作。

在此處輸入圖片說明

例如(根據您的示例數據):

Sub Test()

Dim lr As Long
Dim rng As Range

With Sheet1 'Change according to your sheets CodeName

    'Get your current range
    lr = .Cells(.Rows.Count, 1).End(xlUp).Row
    Set rng = .Range("A1:A" & lr).SpecialCells(xlCellTypeConstants)

    'Loop through each section to sum it
    For Each area In rng.Areas
        area.Offset(area.Rows.Count).Resize(1).Value = Application.Sum(Area)
    Next

End With

End Sub

使用工作表函數SUM這將非常容易,所以我建議使用相同的方法,只需在 VBA(宏代碼)中使用它:

Sub SumRange()
    Dim rng As Range
    ' define range to be summed
    Set rng = Range("A1:A11")
    ' sum range in A12
    Cells(12, 1).Value = Application.WorksheetFunction.Sum(rng)
End Sub

嘗試這個 -

Sub SumRange()


    lastrow = Range("A1000000").End(xlUp).Row

    Start = 1

    For Each c In Range("A2:A" & (lastrow + 1)).Cells

    If c = "" Then

    c.Select

    ActiveCell = Application.WorksheetFunction.Sum(Range(Cells(Start, 1), Cells(ActiveCell.Offset(-1, 0).Row, 1)))
    Start = c.Offset(1, 0).Row


    '''''Color sum cell in green
    With Selection
  With .Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .Color = 5296274
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With

End With





    End If

    Next


End Sub
Dim arr As Variant, El As Variant
Dim i As Long, lngSum As Long

  With ActiveSheet
    arr = .Range("A1:A" & .Cells(.Rows.Count, 1).End(xlUp).Row + 1).value
    For Each El In arr
        i = i + 1
        If El <> "" Then
            lngSum = lngSum + El
        Else
            .Range("A" & i).value = lngSum
            .Range("A" & i).Font.Color = vbRed ' just to easier identify the updated cell
            lngSum = 0
        End If
    Next
  End With
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM