|
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
排序功能使用Recordset来实现相对比较容易,详细代码如下:
Option Explicit
Sub StudentRankByGrades()
'创建Recordset
Dim rs As New ADODB.Recordset
Dim i, j As Integer
Dim fields
fields = Array("学号", "班次", "姓名", "语文", "英语", "数学", "总分", "班排名", "校排名")
'定义字段
Dim s As Variant
For Each s In fields
If s = "姓名" Then
rs.fields.Append s, adVariant
Else
rs.fields.Append s, adInteger
End If
Next
rs.Open
'将数据插入到Recordset中
Dim data
For i = 1 To 4 Step 1
data = Range(Sheets(i).Cells(5, 1), Sheets(i).Cells(Sheets(i).UsedRange.Rows.Count, 9)).Value
For j = 1 To UBound(data)
rs.AddNew fields, Application.Transpose(Application.Transpose(Application.Index(data, j, 0)))
Next
Next
'按照要求排序
rs.Sort = "总分 DESC, 班次 ASC, 学号 ASC"
rs.MoveFirst
'分两栏写入排名前100位的同学
i = 1
With Sheets(5)
While Not rs.EOF
If i > 100 Then
MsgBox "已完成前100位学生的排名。"
Exit Sub
End If
For j = 1 To 6 Step 1
If i > 50 Then
.Cells(i - 50 + 2, j + 7) = rs.fields(j).Value
Else
.Cells(i + 2, j) = rs.fields(j).Value
End If
Next
If i > 50 Then
.Cells(i - 50 + 2, 14) = rs.fields(8)
Else
.Cells(i + 2, 7) = rs.fields(8)
End If
rs.MoveNext
i = i + 1
Wend
End With
MsgBox "已完成学生的排名。"
End Sub
|
|