先添加MSFlexGrid控件,方法:菜单->工程->部件->Microsoft FlexGrid Control 6.0(后面为版本号),代码如下:
Option Explicit
Private Const STR_SORT_ASC = "△"
Private Const STR_SORT_DESC = "▽"
Private Sub Form_Load()
Dim i As Long
'添加一些试验数据
With MSFlexGrid1
.Rows = 51
.Cols = 5
For i = 0 To 50
.TextMatrix(i, 0) = ("Col" & i)
.TextMatrix(i, 1) = ("Col" & i)
.TextMatrix(i, 2) = ("Col" & i)
.TextMatrix(i, 3) = ("Col" & i)
.TextMatrix(i, 4) = ("Col" & i)
Next
End With
End Sub
'排序函数
Public Sub Sort(sgrd As MSFlexGrid, y As Single)
With sgrd
If y >= .RowPos(0) And y < .RowPos(1) Then
If .Tag <> "" Then
If .Tag <> .Col Then
.TextMatrix(0, .Tag) = Left(.TextMatrix(0, .Tag), Len(.TextMatrix(0, .Tag)) - 1)
End If
End If
If Right(.TextMatrix(0, .Col), 1) = STR_SORT_ASC Then
.Sort = flexSortGenericAscending
.TextMatrix(0, .Col) = Replace(.TextMatrix(0, .Col), STR_SORT_ASC, STR_SORT_DESC)
ElseIf Right(.TextMatrix(0, .Col), 1) = STR_SORT_DESC Then
.Sort = flexSortGenericDescending
.TextMatrix(0, .Col) = Replace(.TextMatrix(0, .Col), STR_SORT_DESC, STR_SORT_ASC)
Else
.Sort = flexSortGenericDescending
.TextMatrix(0, .Col) = .TextMatrix(0, .Col) & STR_SORT_ASC
End If
.Tag = .Col
End If
End With
End Sub
Private Sub MSFlexGrid1_MouseUp(Button As Integer, Shift As Integer, x As Single, y As Single)
Sort MSFlexGrid1, y
End Sub