在每张纸上,我想对A3向下的A列求和(没有空单元格),然后将总和插入第一个空单元格中。
下面的代码对于工作表1很好用,但是总和值对于工作表2以上是错误的(在工作表2中,工作表1的总和是加倍的,并且该相同的值也将被插入工作表3)。
如果您能指出我做错了什么,我将不胜感激?
Sub Sum_Dynamic_Rng()
Dim ws As Worksheet
Dim LastCell As Range
For Each ws In ThisWorkbook.Worksheets
Set LastCell = ws.Range("A3").End(xlDown).Offset(1, 0)
LastCell.Formula = WorksheetFunction.Sum(Range(Range("A3"), Range("A3").End(xlDown)))
Next ws
End Sub
答案 0 :(得分:0)
遍历每个工作表时,您必须确定它们的范围。
Sub Sum_Dynamic_Rng()
Dim ws As Worksheet
Dim LastCell As Range
For Each ws In ThisWorkbook.Worksheets
Set LastCell = ws.Range("A3").End(xlDown).Offset(1, 0)
LastCell = WorksheetFunction.Sum(ws.Range(ws.Range("A3"), ws.Range("A3").End(xlDown)))
'if you actually want a sum formula then,
'LastCell.FormulaR1C1 = "=SUM(R3C:R[-1]C)"
Next ws
End Sub
答案 1 :(得分:0)
'*******************************************************************************
' Purpose: In all worksheets starting from the specified first cell
' of a contiguous column range, sums up its values and returns
' the result a specified number of rows below.
'*******************************************************************************
Sub SumUpColumnFromAbove()
Const cStrRange As String = "A3" ' Cell Range Address
Const cLngOffset As Integer = 2 ' Result Offset (1 for first row below)
Dim i As Integer
With ThisWorkbook
For i = 1 To .Worksheets.Count
With .Worksheets(i).Range(cStrRange).Cells(1, 1)
' Check if range has more than one cell (row) i.e.
' the cell below is not empty.
If Not IsEmpty(.Offset(1, 0)) Then ' More than one cell.
.End(xlDown).Offset(cLngOffset, 0) = WorksheetFunction _
.Sum(.Resize(.End(xlDown).Row - 1))
Else ' One cell only.
.Offset(cLngOffset, 0) = WorksheetFunction _
.Sum(.Parent.Range(cStrRange))
End If
End With
Next
End With
End Sub
'*******************************************************************************