如何在无唯一ID的情况下为ListBox2填充平均总时长
问题:按工种计算平均总时长并填充ListBox2
原始Excel数据
| YEAR | ID | Work | Time_In | Time_Out | Total_Hours |
|---|---|---|---|---|---|
| 2023 | 111 | Carpenter | 11:00:00 | 12:00:00 | 1:00:00 |
| 2023 | 111 | Painter | 8:00:00 | 8:30:00 | 0:30:00 |
| 2023 | 112 | Dancer | 9:00:00 | 10:25:00 | 1:25:00 |
| 2023 | 113 | Singer | 10:00:00 | 11:10:00 | 1:10:00 |
| 2023 | 113 | Singer | 11:00:00 | 11:20:00 | 0:20:00 |
| 2023 | 113 | Carpenter | 13:00:00 | 13:10:00 | 0:10:00 |
| 2023 | 114 | Painter | 13:40:00 | 14:00:00 | 0:20:00 |
| 2023 | 114 | Singer | 14:40:00 | 15:35:00 | 0:55:00 |
| 2024 | 111 | Carpenter | 11:00:00 | 11:10:00 | 0: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
代码核心逻辑说明
- 字典统计:用一个字典同时存储每个工种的总时长和去重条目数,额外用
ID_工种作为key确保条目数不重复统计,和你原有的统计逻辑保持一致 - 平均计算:总时长除以对应工种的条目数,通过
Format函数将数值格式化为hh:mm:ss的时间格式 - ListBox配置:设置列数、列宽,先添加表头行,再依次填充每个工种的名称和平均时长
内容的提问来源于stack exchange,提问作者Shiela
相关产品推荐
相关产品推荐

