萬盛學電腦網

 萬盛學電腦網 >> Excel教程 >> excel綜合 >> excel雙擊列標題自動排序的VBA代碼

excel雙擊列標題自動排序的VBA代碼

   通過以下的VBA代碼,將其放到工作表的雙擊事件中,就能取到雙擊工作表的列標題(雙擊列的名字),當前列自動進行排序。

  比如,將代碼放在如下的事件中:

  Private Sub Worksheet_SelectionChange(ByVal Target As Range)

  End Sub

  代碼如下:

  Dim YouRg As Range

  If Target.Column <= Me.Cells (1,1).CurrentRegion.Columns.Count And Target.Row = 1 Then

  If Target.Column <> mnColumn Then

  mnColumn = Target.Column

  mnDirection = xlAscending

  Else

  If mnDirection = xlAscending Then

  mnDirection = xlDescending

  Else

  mnDirection = xlAscending

  End If

  End If

  Set YouRg = Me.Cells(1, 1).CurrentRegion

  YouRg .Sort key1:=YouRg .Cells(1, mnColumn), order1:=mnDirection,header:=xlYes

  Set YouRg = Nothing

  Cancel = True

  End If

  以上代碼是升序排序,你可以改為降序排序。

copyright © 萬盛學電腦網 all rights reserved