-1

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

4

1 回答 1

0

编辑:

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

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()正常工作。这应该在您打开工作簿时发生。

该代码大量借鉴了其他人的工作,即:
如何在按下 Refresh 或 Refresh All 按钮后调用宏?由@Rory 回答

微软文档

于 2015-11-08T21:49:00.363 回答