合并2列以获得唯一值以输出总和

时间:2019-06-14 14:57:00

标签: excel vba

如果列A =“ EAST01”,然后合并或列“ B”和“ C”,我想使用下面的数据获取列“ A”中的特定值,计算列“ I”中输出的唯一出现次数“(TOTAL_TRAILERS)并将“ D”列(DOCK_TIME)中的值求和,并在“ J”列中输出(TOTAL_DOCK_TIME)

到目前为止,这段代码产生的结果为我提供了唯一的值,但我一直在努力找出在何处插入if语句以仅获取'EAST01'和计算以获取输出。 由于我每天都会收到此文件,因此我希望附加输出不要覆盖我之前的输出,而是在下一个行中的“ TOTAL_TRAILERS”和“ TOTAL_DOCK_TIME”下打印。 任何帮助将不胜感激。

样本数据

STORE   TRAILER REC_DATE            DOCK_TIME
EAST01  648295  6/7/2019 10:12:13 AM    19
WEST03  671649  6/7/2019 10:14:47 AM    18
CENTRAL1 V18070 6/7/2019 10:23:31 AM    21
SOUTH04 671652  6/7/2019 10:27:59 AM    22
EAST01  648295  6/7/2019 10:54:12 AM    22
EAST01  648295  6/7/2019 12:03:04 PM    24
EAST01  62517   6/7/2019 12:03:37 PM    23

Sub unikAndSum()

    Dim i As Long, N As Long, s As String, r As Range
    'Set ws = ThisWorkbook.ActiveSheet
    'With ws
    'N=.Range("A" & .rows.count.end(xlup).row
    N = Cells(Rows.Count, "A").End(xlUp).Row
    For i = 2 To N
        Cells(i, 5) = Cells(i, 2) & " " & Cells(i, 3)
        Cells(i, 6) = Cells(i, 5)
    Next i
    'Range("F:F").RemoveDuplicates Columns:=1, Header:=xlNo
    For Each r In Range("F:F").SpecialCells(2).Offset(, 1)
        r.Formula = "=COUNTIF(E:E," & r.Offset(, -1).Address & ")"
    Next r
End Sub

       TOTAL_TRAILER           TOTAL_DOCK_TIME
                  4                        88

第二天在这里输出>

1 个答案:

答案 0 :(得分:0)

您要查找的值EAST01在Cells(i,1)中

If语句在For循环中

已修改,以回应有关计数降低程序速度的后续问题。

您可以消除for循环,因为countif语句所做的只是在G列中放入1。无需执行countif,只需在if语句中的G列中放入1。

Cells(i,7)= 1

    Sub unikAndSum()

    Dim i As Long, N As Long, s As String, r As Range
    'Set ws = ThisWorkbook.ActiveSheet
    'With ws
    'N=.Range("A" & .rows.count.end(xlup).row
    N = Cells(Rows.Count, "A").End(xlUp).Row
    For i = 2 To N
        If (Cells(i, 1) = "EAST01") Then
        Cells(i, 5) = Cells(i, 2) & " " & Cells(i, 3)
        Cells(i, 6) = Cells(i, 5)
        Cells(i, 7) = 1
        End If
    Next i
    'Range("F:F").RemoveDuplicates Columns:=1, Header:=xlNo

    'For Each r In Range("F:F").SpecialCells(2).Offset(, 1)
    '    r.Formula = "=COUNTIF(E:E," & r.Offset(, -1).Address & ")"
    'Next r

End Sub