正如其他人所说,数据透视表确实是最好的方法。如果您不确定如何使用数据透视表或其优点,请致电refer to this SO post where I explain in detail。
无论如何,我将下面的VBA函数放在一起,以帮助您入门。这绝不是最有效的方法;这也使得以下假设:
Sheet 1
有
A
有工作人员用ID
B
有时间
C
保留用于总学时中的所有数据
D
将可处理状态输出
这当然可以通过修改代码很容易地改变。审查代码,它的评论让你明白。
Status
列必须存在的原因是为了避免处理已经处理的Staff Id
。你可以改变代码以避免需要这个列,但这是我处理事情的方式。
CODE
Public Sub HoursForEmployeeById()
Dim currentStaffId As String
Dim totalHours As Double
Dim totalStaffRows As Integer
Dim currentStaffRow As Integer
Dim totalSearchRows As Integer
Dim currentSearchRow As Integer
Dim staffColumn As Integer
Dim hoursColumn As Integer
Dim totalHoursColumn As Integer
Dim statusColumn As Integer
'change these to appropriate columns
staffColumn = 1
hoursColumn = 2
totalHoursColumn = 3
statusColumn = 4
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
totalStaffRows = Sheet1.Cells(Rows.Count, staffColumn).End(xlUp).Row
For currentStaffRow = 2 To totalStaffRows
currentStaffId = Cells(currentStaffRow, staffColumn).Value
'if the current staff Id was not already processed (duplicate record)
If Not StrComp("Duplicate", Cells(currentStaffRow, statusColumn).Value, vbTextCompare) = 0 Then
'get this rows total hours
totalHours = CDbl(Cells(currentStaffRow, hoursColumn).Value)
'search all subsequent rows for duplicates
totalSearchRows = totalStaffRows - currentStaffRow + 1
For currentSearchRow = currentStaffRow + 1 To totalSearchRows
If StrComp(currentStaffId, Cells(currentSearchRow, staffColumn), vbTextCompare) = 0 Then
'duplicate found: log the hours worked, set them to 0, then mark as Duplicate
totalHours = totalHours + CDbl(Cells(currentSearchRow, hoursColumn).Value)
Cells(currentSearchRow, hoursColumn).Value = 0
Cells(currentSearchRow, statusColumn).Value = "Duplicate"
End If
Next
'output total hours worked and mark as Processed
Cells(currentStaffRow, totalHoursColumn).Value = totalHours
Cells(currentStaffRow, statusColumn).Value = "Processed"
totalHours = 0 'reset total hours worked
End If
Next
Application.ScreenUpdating = False
Application.Calculation = xlCalculationAutomatic
End Sub
BEFORE
AFTER
来源
2013-03-14 17:38:38
Sam
您是否尝试过任何操作?你真的需要用VBA来做,因为数据透视表可能足以解决你的问题 – 2013-03-14 16:31:31
确实使用数据透视表,问题解决了我猜... – 2013-03-14 16:34:05
确切地说,使用数据透视表来分组和总结你的数据。 – 2013-03-14 16:51:38