将固定起始单元格的列汇总到最后一列VBA

时间:2018-06-25 16:13:58

标签: vba

我有一个表格,该表格每次运行都会改变大小。我希望最后一列返回每一行所有值的总和。该表的最后一行返回我尝试编辑的每列的总和,以便它将返回最后一列中的行的总和

'Sums everything starting from "L16" to the last row in column L and drags formula across the last row until the last column
Range(Cells(LR, "L"), Cells(LR, lastcol)).Formula = "=sum(L16:L" & LR - 1 & ")"
'Doesn't work but I want it to sum everything starting from "L16" to the last column in row 16 and drag the formula to the last row
Range(Cells(16, lastcol), Cells(LR, lastcol)).Formula = "=sum(L16:16" & lastcol-1 & ")"

2 个答案:

答案 0 :(得分:0)

=sum(L16:16" & lastcol-1 & ")此处存在语法错误,您需要在行号之前输入列字母。

如果您的lastcol不大于27,则可以使用以下语句:

Range(Cells(16, lastcol), Cells(LR, lastcol)).Formula = "=sum(L16:" & Chr(lastcol - 1 + 64) & "16)"

或者,将此功能添加到您的项目中:

Function ColLetter(Col As Long) As String
    Dim vArr
    vArr = Split(Cells(1, Col).Address(True, False), "$")
    ColLetter = vArr(0)
End Function

它返回您提供的任何列号的字母。 然后在您的代码中可以像这样使用它:

Range(Cells(16, lastcol), Cells(LR, lastcol)).Formula = "=sum(L16:" & ColLetter(lastcol - 1) & "16)

答案 1 :(得分:0)

不确定数据的起始位置,但可以使用iStartCol和iStartRow进行设置。它将在每一行和每一列的末尾加上一个求和公式,也就是一个总计。

Sub Test()
Dim iStartCol As Long
Dim iStartRow As Long
iStartCol = 2       ' Starting Column of your Data
iStartRow = 11      ' Starting Row of your Data

Dim iTotalCol As Long   ' Find where the Total Column will be
iTotalCol = Sheet1.UsedRange.Columns.Count + 1

Dim iTotalRow As Long   ' Find where the Total Row will be
iTotalRow = Sheet1.UsedRange.Rows.Count + 1

' Total Row
Sheet1.Range(Cells(iTotalRow, iStartCol), Cells(iTotalRow, iTotalCol - 1)).Formula = "=Sum(R[-" & iTotalRow - iStartRow & "]C:R[-1]C)"

' Total Cols
' Note: no -1 in Range so we will also sum the Total Row, for grand total
Sheet1.Range(Cells(iStartRow, iTotalCol), Cells(iTotalRow, iTotalCol)).Formula = "=Sum(RC[-" & iTotalCol - iStartCol & "]:RC[-1])"
End Sub