汇总表中的列值

时间:2015-10-27 14:28:36

标签: excel vba

我有按钮可以添加行,撤消上次添加的行并删除表中的所有行。最后,我有一个按钮,应该在表的末尾添加一行,它总结了上面列的内容。

Private Sub cmbSummarizeColumns_Click()
Dim the_sheet As Worksheet
Dim table_list_object As ListObject
Dim table_object_row As ListRow

Set the_sheet = Sheets("Ark1")
Set table_list_object = the_sheet.ListObjects(1)
Set table_object_row = table_list_object.ListRows.Add

table_object_row.Range(1, 1).Value = sumcolumn_1
table_object_row.Range(1, 2).Value = sumcolumn_2
table_object_row.Range(1, 3).Value = sumcolumn_3
End Sub

我不知道如何找到第1,2和3栏的总和,因为我对VBA来说还是个新手。是的,我在这张表中有标题。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

如果您要为总计添加一行,您也可以添加结构化ListObject TotalsRowRange property

Private Sub cmbSummarizeColumns_Click()
    Dim the_sheet As Worksheet
    Dim table_list_object As ListObject
    Dim tblCOL As Long

    Set the_sheet = Sheets("Sheet6")
    Set table_list_object = the_sheet.ListObjects(1)

    With table_list_object
        If Not .ShowTotals Then .ShowTotals = True
        For tblCOL = 1 To 3   'might use To .DataBodyRange.Columns.Count
            .TotalsRowRange.Cells(1, tblCOL) = _
              Application.Sum(.DataBodyRange.Columns(tblCOL))
        Next tblCOL
    End With
End Sub

您提供的示例似乎表明您希望对总和值进行硬编码。如果您想要SUM functionSUBTOTAL function,那么将公式替换为VBA评估公式返回的值应该很容易。