对于商店中的每个员工来说,都有一个任务。如果员工完成了任务,则在“商店”的“任务”列中具有“ 1”。我必须将每个商店的所有“ 1”加起来,并检查每个商店的任务完成百分比。下面给出示例:
Shop Task
1002 0
1002 1
1002 0
1002 0
1002 0
1008 1
1008 1
1008 1
1008 1
etc...
我不知道如何创建一个循环,以完成随[Shop]更改而更改的总数和百分比 。非常感谢。
答案 0 :(得分:1)
我怀疑这实际上是否比SUMIF快,但是它确实可以一遍收集商店标识符以及总数。
sub shopTotals()
dim i as long, arr as variant, dict as object
set dict = createobject("scripting.dictionary")
dict.comparemode = vbtextcompare
with worksheets("sheet1")
arr = .range(.cells(2, "A"), .cells(.rows.count, "B").end(xlup)).value2
for i=lbound(arr, 1) to ubound(arr, 1)
dict.item(arr(i, 1)) = dict.item(arr(i, 1)) + arr(i, 2)
next i
.cells(2, "D").resize(dict.count, 1) = application.transpose(dict.keys)
.cells(2, "E").resize(dict.count, 1) = application.transpose(dict.items)
end with
end sub
AVERAGEIF或COUNTIF可以检索其他统计信息。
答案 1 :(得分:0)
答案 2 :(得分:0)
这是一个示例循环,说明如何使用字典对象和变量数组。有时,使用VBA 100%代码实现业务逻辑会更容易。您可以在循环行时做所有事情。此示例仅打印出[0]total,[1]=countIfOne values per Key
数组。
' Tools/References: [x]Microsoft Scripting Runtime
Public Sub sumShops()
Dim ws As Worksheet
Dim arr As Scripting.Dictionary
Dim iRow As Long
Dim val As String
Dim item As Variant
Set arr = New Scripting.Dictionary
Set ws = Application.Worksheets("Shops")
For iRow = 2 To ws.UsedRange.Rows.Count
val = Trim(ws.Cells(iRow, 1)) ' 1001,1002,..
If Not arr.Exists(val) Then
ReDim item(0 To 1) As Long
item(0) = 0 ' total count
item(1) = 0 ' count if task=1
Call arr.Add(val, item)
Else
item = arr.item(val)
End If
item(0) = item(0) + 1
If ws.Cells(iRow, 2).Value = "1" Then item(1) = item(1) + 1 ' count task=1 rows
' we must reference array back to the dictionary key
arr(val) = item
Next
' Loop dictionary by keys and print an array(0..1)
For iRow = 0 To arr.Count - 1
val = arr.Keys(iRow)
item = arr.item(val)
Debug.Print val & "=" & item(0) & "," & item(1)
Next
End Sub
答案 3 :(得分:0)