您当前的位置: 首页 > 办公软件教程 > Excel教程 浏览
excel双击列标题自动排序的VBA代码
发布时间:2015-10-25    点击率:次    来源:www.sytcke.com    作者:电脑技术学习网

   通过以下的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

  以上代码是升序排序,你可以改为降序排序。

发表留言
发表留言请先登录!
免责声明:本站发布的信息和评论纯属网民个人行为,并不代表本站立场,如发现有违法信息或侵权行为,请直接与本站管理员联系,我们将在收到您的信息后24小时内作出处理!