我在Excel中有以下数据集(工作表名称:'WorkingSheet')
| A | B | C | D | E
1| 14 October 2013 | Mon | 9:28:30 | 0:19:14 |
2| 15 October 2013 | Tue | 9:25:20 | 0:05:39 |
3| 16 October 2013 | Wed | 9:29:07 | 0:06:58 |
4| 17 October 2013 | Thu | 9:27:02 | 0:04:25 |
5| 18 October 2013 | Fri | 9:32:11 | 0:01:29 |
6| 19 October 2013 | Sat | 9:28:08 | 3:12:45 | 60:40:48
7| 20 October 2013 | Sun | 7:59:41 | 0:00:00 | 7:59:41
8| 21 October 2013 | Mon | 9:26:52 | 0:13:42 |
9| 22 October 2013 | Tue | 9:26:51 | 0:14:32 |
10| 23 October 2013 | Wed | 9:35:06 | 0:08:14 |
11| 24 October 2013 | Thu | 9:19:13 | 0:10:49 |
12| 25 October 2013 | Fri | 6:50:44 | 3:06:47 | 48:32:50
13| 28 October 2013 | Mon | 9:30:21 | 0:11:49 |
14| 29 October 2013 | Tue | 9:46:43 | 0:09:27 |
15| 30 October 2013 | Wed | 9:28:31 | 0:15:15 |
16| 31 October 2013 | Thu | 9:31:04 | 0:16:04 | 39:09:14
我想将VBA脚本放在一起,计算'E'中的值。
'E'需要将星期一到星期六(或星期几的最后一天)的'C'和'D'中的值相加(E6 = SUM(C1:D6)) 对于星期日,只等于那一天(星期日)的总和
可以这样做吗?
我是所有这一切的新手所以请原谅我这是一个愚蠢的问题。
如果您还想了解其他信息,请告诉我们。
非常感谢。
编辑:加法。
好的,所以我正试图从我发现的点点滴滴做出一些改进,到目前为止,我有这个:
Sub Macro1()
Dim lw As Long
Dim c As Range
Dim hDate As Date
Dim hc As Range
hDate = dhLastDayInWeek(Range("A1"))
lw = Range("A" & Rows.count).End(xlUp).Row
For Each c In Range("A1:A" & lw)
If dhLastDayInWeek(c.Value) = hDate Then
Else
c.Offset(-1, 5).Value = Application.Sum(Range("C1:C27"))
hDate = dhLastDayInWeek(CDate(c))
End If
Next c
End Sub
使用此功能查找日期
Function dhLastDayInWeek(Optional dtmDate As Date = 0) As Date
' Last Day being Saturday +6
dhLastDayInWeek = dtmDate - Weekday(dtmDate, vbUseSystem) + 6
End Function
我现在只需要弄清楚如何将Application.Sum(Range(“C1:C27”))更改为从hDate Cell到日期不等的总和。
到达那里,从来没有因为从未这样做过:S
答案 0 :(得分:2)
这给出了一个好结果:
当您将列A定义为DateTime值时,我们遍历此列,直到找到空单元格。 C和D列是 hh:mm:ss 格式的时间值。
Sub sof20193038SumPerWeek()
Dim i, wDay, wDayLast, dblTotal
Dim bEmpty
Dim dtmDate
i = 1
wDayLast = -1
bEmpty = False
dblTotal = 0
Do While (Not bEmpty)
dtmDate = Range("A" & i).Value
bEmpty = IsEmpty(dtmDate)
If (bEmpty) Then
Range("E" & (i - 1)).Value = dblTotal
Exit Do
End If
'
' get the weekday in [1,7]:
'
wDay = Weekday(dtmDate, vbMonday)
'
' last existent weekday, neither saturday nor sunday:
'
If (wDay < wDayLast) Then
If (Not ((wDayLast = 6) Or (wDayLast = 7))) Then
Range("E" & (i - 1)).Value = dblTotal
dblTotal = 0
End If
End If
'
' sum up C and D columns:
'
dblTotal = dblTotal + Range("C" & i).Value + Range("D" & i).Value
'
' weekend: ie, saturday or sunday:
'
If ((wDay = 6) Or (wDay = 7)) Then
Range("E" & i).Value = dblTotal
dblTotal = 0
Else
Range("E" & i).Value = Null
End If
'
wDayLast = wDay
'
' prepare for the next row:
'
i = i + 1
Loop
End Sub