|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
这个需求用函数显然很难满足了。就事论事地用代码解决——
第一个需求,统计工作小时合计,做一个简单的自定义函数:
- Function hsum(rng As Range)
- On Error Resume Next
- Dim k As Range, arr, d!
- If rng Is Nothing Then Exit Function
- For Each k In rng
- If Len(k) > 0 Then
- arr = Split(k, "-")
- d = d + Hour(CDate(arr(1)) - CDate(arr(0))) + Minute(CDate(arr(1)) - CDate(arr(0))) / 60
- End If
- Next
- hsum = Round(d, 2)
- End Function
复制代码 第二个需求,用一个宏解决,报表生成在“Sheet2",用了太多循环,算法没优化,数据量大的情况下,可能运算时间长:
- Sub report()
- On Error Resume Next
- Dim k As Range, i%, m%, arr(1 To 9999, 1 To 4)
- '获取数据清单
- With Sheet1
- For Each k In Range(.Cells(3, 1), .Cells(.[A65536].End(xlUp).Row, 1))
- For i = 1 To 7
- If Len(.Cells(k.Row, i + 1)) > 0 And Not IsNumeric(.Cells(k.Row, i + 1)) Then
- m = m + 1
- arr(m, 1) = k.Value
- arr(m, 2) = Application.Text(i, "dddd")
- arr(m, 3) = CDate(Split(.Cells(k.Row, i + 1), "-")(0))
- arr(m, 4) = CDate(Split(.Cells(k.Row, i + 1), "-")(1))
- End If
- Next i
- Next
- End With
- '提炼生成报表
- Dim arrR(1 To 18, 1 To 15), j%, x%, a%, b$
- For i = 1 To 16
- arrR(i + 2, 1) = Format(5 + i, "00") & ":00-" & Format(6 + i, "00") & ":00" '写入左标题
- For j = 2 To 14 Step 2
- '写入顶端标题
- arrR(1, j) = Application.Text(j / 2, "dddd")
- arrR(2, j) = "员工数"
- arrR(2, j + 1) = "员工名单"
- '查询数据
- a = 0
- b = ""
- For x = 1 To m
- If arr(x, 2) = Application.Text(j / 2, "dddd") And Hour(arr(x, 3)) <= i + 5 And Hour(arr(x, 4)) >= i + 6 Then
- a = a + 1
- b = b & arr(x, 1) & ","
- End If
- Next
- arrR(i + 2, j) = a
- arrR(i + 2, j + 1) = Left(b, Len(b) - 1)
- Next
- Next
- '写入最终报表
- With Sheet2
- .Cells.ClearContents
- .[A1].Resize(18, 15) = arrR
- End With
- End Sub
复制代码 具体效果看附件吧,不啰嗦了!
|
-
-
ask.rar
17.66 KB, 下载次数: 40
含有宏,打开需要启用宏
|