You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在无唯一ID的情况下为ListBox2填充平均总时长

问题:按工种计算平均总时长并填充ListBox2

原始Excel数据

YEARIDWorkTime_InTime_OutTotal_Hours
2023111Carpenter11:00:0012:00:001:00:00
2023111Painter8:00:008:30:000:30:00
2023112Dancer9:00:0010:25:001:25:00
2023113Singer10:00:0011:10:001:10:00
2023113Singer11:00:0011:20:000:20:00
2023113Carpenter13:00:0013:10:000:10:00
2023114Painter13:40:0014:00:000:20:00
2023114Singer14:40:0015:35:000:55:00
2024111Carpenter11:00:0011:10:000:10:00

已实现用标签统计各工种的去重条目数,现需给ListBox2填充每个工种的平均总时长,以下是解决方案:

修改后的完整代码

Option Explicit

Sub firstlistdisplay()
    Dim ws As Worksheet
    Dim lastRow As Long
    Dim workTypes As Variant
    Dim i As Long
    Dim dictStats As Object
    Dim key As Variant
    Dim avgHours As Double
    
    workTypes = Array("Carpenter", "Painter", "Dancer", "Singer")
    
    ' 初始化字典,存储每个工种的总时长、条目数
    Set dictStats = CreateObject("Scripting.Dictionary")
    For Each key In workTypes
        dictStats(key) = Array(0, 0) ' 索引0:总时长;索引1:条目数
    Next key
    
    Set ws = ThisWorkbook.Worksheets("Sheet2")
    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    
    ' 遍历数据,统计总时长和去重条目数
    For i = 2 To lastRow ' 跳过表头行
        Dim workName As String
        workName = ws.Cells(i, 3).Value
        Dim uniqueID As String
        uniqueID = ws.Cells(i, 2).Value & "_" & workName
        
        ' 仅当该ID+工种未被统计时,条目数+1
        If Not dictStats.Exists(uniqueID) Then
            dictStats(uniqueID) = True ' 标记已统计
            dictStats(workName)(1) = dictStats(workName)(1) + 1
        End If
        ' 累加总时长
        dictStats(workName)(0) = dictStats(workName)(0) + ws.Cells(i, 6).Value
    Next i
    
    ' 更新标签的条目数
    Me.Label1.Caption = dictStats("Carpenter")(1)
    Me.Label2.Caption = dictStats("Painter")(1)
    Me.Label3.Caption = dictStats("Dancer")(1)
    Me.Label4.Caption = dictStats("Singer")(1)
    
    ' 填充ListBox2的平均时长
    With Me.ListBox2
        .Clear
        .ColumnCount = 2
        .ColumnWidths = "100,80" ' 设置列宽
        ' 添加表头
        .AddItem "工种"
        .List(0, 1) = "平均总时长"
        
        ' 计算并添加每个工种的平均时长
        For Each key In workTypes
            If dictStats(key)(1) > 0 Then
                avgHours = dictStats(key)(0) / dictStats(key)(1)
                .AddItem key
                .List(.ListCount - 1, 1) = Format(avgHours, "hh:mm:ss")
            Else
                .AddItem key
                .List(.ListCount - 1, 1) = "00:00:00"
            End If
        Next key
    End With
End Sub

代码核心逻辑说明

  1. 字典统计:用一个字典同时存储每个工种的总时长和去重条目数,额外用ID_工种作为key确保条目数不重复统计,和你原有的统计逻辑保持一致
  2. 平均计算:总时长除以对应工种的条目数,通过Format函数将数值格式化为hh:mm:ss的时间格式
  3. ListBox配置:设置列数、列宽,先添加表头行,再依次填充每个工种的名称和平均时长

内容的提问来源于stack exchange,提问作者Shiela

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 11:49:56