|
- Sub ClassScoreSectionStatistics()
- Dim wsSource As Worksheet, wsResult As Worksheet
- Dim dataRange As Range
- Dim rowCount As Long, colClass As Long, colScore As Long
- Dim scoreSections As Variant
- Dim classDict As Object
- Dim i As Long, j As Long, k As Long
- Dim classKey As Variant
- Dim rowOutput As Long
- Dim score As Double
-
- ' 引用工作表
- Set wsSource = ThisWorkbook.Sheets("Sheet1")
- Set wsResult = ThisWorkbook.Sheets("结果")
-
- ' 获取数据源范围 (从 A1 开始,包含标题)
- Set dataRange = wsSource.Range("A1").CurrentRegion
- rowCount = dataRange.Rows.Count
-
- ' 定义分数段规则 (根据需求修改)
- scoreSections = Array("3500-3000 (410-420)", "3000-2500 (420-432)", "2500-2000 (432-445)", _
- "2000-1500 (445-460)", "1500-1200 (460-485)", "1200-900 (485-500)", _
- "900-600 (500-521)", "600-300 (521-550)", "300- (550-9999)")
- Dim scoreLimits() As Variant
- scoreLimits = Array(410, 420, 432, 445, 460, 485, 500, 521, 550, 9999) ' 分数段的实际分界点
-
- ' 找到“班级”和“总分”列 (假设标题在第一行)
- colClass = 0
- colScore = 0
- For i = 1 To dataRange.Columns.Count
- If dataRange.Cells(1, i).Value = "班级" Then colClass = i
- If dataRange.Cells(1, i).Value = "总分" Then colScore = i
- Next i
-
- If colClass = 0 Or colScore = 0 Then
- MsgBox "未在标题中找到‘班级’列或‘总分’列,请检查标题!", vbExclamation
- Exit Sub
- End If
-
- ' 初始化用于存储结果的字典
- Set classDict = CreateObject("Scripting.Dictionary")
-
- ' 遍历数据源,从第二行开始
- For i = 2 To rowCount
- ' 确保 classKey 是字符串
- classKey = CStr(dataRange.Cells(i, colClass).Value)
-
- ' 确保分数是有效数字
- If IsNumeric(dataRange.Cells(i, colScore).Value) Then
- score = CDbl(dataRange.Cells(i, colScore).Value)
- Else
- score = 0 ' 如果分数无效,可以跳过或赋默认值
- End If
-
- ' 如果字典中不存在班级,则初始化班级的分段计数
- If Not classDict.exists(classKey) Then
- Dim sectionArray() As Long
- ReDim sectionArray(0 To UBound(scoreSections)) ' 初始化数组
- Dim sectionIndex As Long
- For sectionIndex = 0 To UBound(scoreSections)
- sectionArray(sectionIndex) = 0
- Next sectionIndex
- classDict.Add classKey, sectionArray ' 添加键值对
- End If
- ' 根据分数找到对应的分数段,并计数加1
- For k = 0 To UBound(scoreLimits) - 1
- If score >= scoreLimits(k) And score < scoreLimits(k + 1) Then
- Dim tempArray() As Long
- tempArray = classDict(classKey) ' 获取当前班级的分段计数数组
- tempArray(k) = tempArray(k) + 1
- classDict(classKey) = tempArray ' 更新字典中的数组
- Exit For
- End If
- Next k
- Next i
-
- ' 清空结果工作表
- wsResult.Cells.Clear
-
- ' 输出结果到‘结果’工作表
- wsResult.Cells(1, 1).Value = "班级"
- For j = 0 To UBound(scoreSections)
- wsResult.Cells(1, j + 2).Value = scoreSections(j)
- Next j
-
- rowOutput = 2
- For Each classKey In classDict.keys
- wsResult.Cells(rowOutput, 1).Value = classKey
- For k = 0 To UBound(scoreSections)
- wsResult.Cells(rowOutput, k + 2).Value = classDict(classKey)(k)
- Next k
- rowOutput = rowOutput + 1
- Next classKey
-
- MsgBox "统计完成!", vbInformation
- End Sub
复制代码 |
|