现在有的代码只能在当前工作表上,希望各位老师修改一下代码,并且只计算“在职”的人数,“离职”的不在计算范围内,最终将结果放在sheet2的工作内,并增加序号,附上代码:Sub 计算结果() Set d = CreateObject("scripting.dictionary") Set dnm = CreateObject("scripting.dictionary") Set dt = CreateObject("scripting.dictionary") arr = [b2].CurrentRegion For j = 2 To UBound(arr) d((arr(j, 2)) & arr(j, 4)) = d((arr(j, 2)) & arr(j, 4)) + 1 dt(arr(j, 2)) = "" dnm(arr(j, 4)) = "" Next j If dnm.Count > 0 And dt.Count > 0 Then Application.ScreenUpdating = False [j4].Resize(dt.Count) = WorksheetFunction.Transpose(dt.keys) arr = [j3].CurrentRegion For j = 2 To UBound(arr, 1) For i = 2 To UBound(arr, 2) arr(j, i) = d((arr(j, 1)) & arr(1, i)) Next i Next j [j3].CurrentRegion = arr [j3].CurrentRegion.Borders.LineStyle = xlContinuous Application.ScreenUpdating = True End IfEnd Sub
如果你想在VBA代码中修改筛选后统计"在职"员工人数,并将计算结果放到sheet2中,可以这样做:
在Sheet1中打开VBA编辑器:按Alt + F11。
在VBA编辑器中,点击插入模块。
输入以下代码:
Sub CountEmployees()
Dim lRow As Long
Dim i As Long
Dim count As Long
'获取数据范围
lRow = Cells(Rows.Count, 1).End(xlUp).Row
'遍历每一行
For i = 1 To lRow
'如果员工状态为"在职"
If Cells(i, 2) = "在职" Then
'计数器加一
count = count + 1
End If
Next i
'在Sheet2中插入计数器的值
Sheets("Sheet2").Cells(1, 1) = count
End Sub
在VBA编辑器中运行代码:按F5。
返回到sheet2中查看结果。
以上代码假设数据存储在Sheet1中,员工状态在第二列,并且需要对每行进行遍历,如果员工状态为"在职",则将计数器加一。最后,将计数器的值插入到Sheet2的第1行第1列。