vba范围的总和

时间:2019-07-18 12:35:35

标签: excel vba

说,我在一张纸上有一个类似下面的数据,

Name        Date    time 1   time 2  time 3 time 4  
DA_BAB      02/11/2019   6        1       0      1
DA_GMO      02/11/2019   4        3       5      0 
            02/11/2019   1        2       1      1 
DA_GMO      02/11/2019   2        1       1      4 
Lloyd       02/11/2019   0        2       0      0

我必须根据名称分组,并始终将其汇总在vba中的一个类别下。

例如DA_BAB为8,Lloyd为2,依此类推。

我真的是vba的新手,不知道该怎么写。有人可以帮我吗?

我试图创建一个函数并调用该函数,但是它不起作用

当我们对数据进行分组时,我们应该如下所示

DA_BAB是8,Lloyd是2,依此类推。

1 个答案:

答案 0 :(得分:0)

如果您的数据放在A至F列之间,则以下代码将为您提供I&J列中的摘要,这将为您提供所需的结果。

如果行中的任何一行实际上不包含任何内容,我现在添加一条语句以使用以前的名称:

Sub Combine()
Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Sheet1")
'declare and set the worksheet you are working with, amend as required
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
'get the last row with data on Column A

For Each c In ws.Range("A2:A" & LastRow).Cells
'loop through column A to get unique Names
    If c.Value = "" Then
    'if value is empty then use previous value
        Valu = ws.Cells(c.Row - 1, "A").Value
    Else
        Valu = c.Value
    End If

    Set FoundVal = ws.Range("I:I").Find(What:=Valu, LookAt:=xlWhole)
    'see if name already exists in Column I
    If FoundVal Is Nothing Then
    'if name not found
        newRow = ws.Cells(ws.Rows.Count, "I").End(xlUp).Row + 1
        'get the next free row on column I
        ws.Cells(newRow, "I").Value = c.Value
        'add new name
        ws.Cells(newRow, "J").Value = ws.Cells(newRow, "J").Value + ws.Cells(c.Row, "C").Value + ws.Cells(c.Row, "D").Value + ws.Cells(c.Row, "E").Value + ws.Cells(c.Row, "F").Value
        'add new name
    Else
        ws.Cells(FoundVal.Row, "J").Value = ws.Cells(FoundVal.Row, "J").Value + ws.Cells(FoundVal.Row, "C").Value + ws.Cells(FoundVal.Row, "D").Value + ws.Cells(c.Row, "E").Value + ws.Cells(FoundVal.Row, "F").Value
    End If
Next
ws.Range("I1").Value = "Name"
ws.Range("J1").Value = "Totals"
End Sub