【问题标题】:After data refresh sort column A alphabetically数据刷新后按字母顺序排列A列
【发布时间】:2015-11-08 15:17:56
【问题描述】:

我的 Excel 电子表格有点问题,希望有人能提供帮助。我的名字从 Cell=A7 开始,到 A177。所有其他信息都在列 (B:H) 中。理想情况下,我想在点击数据刷新后运行代码。我正在使用这张表,所以我可以查找另一张表的信息,因此它需要按字母顺序 A-Z。信息来自网络查询。

【问题讨论】:

  • 录制宏:刷新数据->按照您的意愿排序->停止录制...使用宏重复此操作:D

标签: excel excel-web-query vba


【解决方案1】:

编辑:

将以下代码添加到标准模块。查看代码中的编辑以确保它按预期正确地将所有列排序在一起。

Option Explicit

dim DataTable as New Class1

Sub Auto_Open()
'This will run automatically when the workbook is opened, so macros will need to be enabled. 

'Select any cell in the data table.
Activesheet.Range("A7").Select
Set DataTable.qt = ThisWorkbook.ActiveSheet.QueryTables(1)
Sub

Sub AutoSort()
Dim rng As Range
Dim Nrow As Integer
Dim Ncol As Integer
Dim WS As Worksheet

'Assume that the active sheet contains the data that you want to sort
'Since it sounds like you'll be calling this from another macro, this
'is probably not a good assumption.
Set WS = ActiveWorkbook.ActiveSheet

'Get the row number of your last entry in column A, then the right most
'column of your data. Assume there is no other data on this worksheet.
Nrow = WS.Cells(Rows.Count, "A").End(xlUp).Row '177 in your case

'Replace the following line
'Ncol = WS.Cells(1, Columns.Count).End(xlToLeft).Column '8 in your case
'with this line
Ncol = WS.Cells(7, Columns.Count).End(xlToLeft).Column '8 in your case

'set all of your data in a range.
Set rng = WS.Range(Cells(7, 1), Cells(Nrow, Ncol))

'the actual sorting
rng.Sort key1:=rng, order1:=xlAscending, Header:=xlYes

End Sub

然后创建一个类模块,插入如下代码:

Option Explicit

Public WithEvents qt As QueryTable

Private Sub qt_AfterRefresh(ByVal Success As Boolean)

    If Success = True Then

        Call Module1.AutoSort
        MsgBox "Data was updated and sorted."

    End If

End Sub

请注意,Auto_Open() 必须先运行,AutoSort() 才能正常工作。这应该在您打开工作簿时发生。

代码大量借鉴了其他人的工作,即:
How to call macro after Refresh or Refresh All button pressed?@Rory 回答

Microsoft Documentation

【讨论】:

  • 感谢 JJC 的回复。该代码非常适合对 A 列中的名称进行排序,但是,它不会在 DATA REFRESH 时自动执行此操作,而且 B:H 列中的所有数据也不会按名称排序。所以基本上名字旁边的数据是错误的。任何帮助将不胜感激。
  • @DomsDad18,我编辑了我的答案以解决您指出的排序问题。我还添加了一些代码,使其在数据连接刷新后自动运行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 2020-09-03
  • 1970-01-01
  • 2020-03-29
相关资源
最近更新 更多