2015-11-08 97 views
-1

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

+1

录制宏:刷新数据 - >排序像你希望它是 - >停止录制...使用宏重复这个动作:D –

回答

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

的代码是大量绘图他人的工作,即:
How to call macro after Refresh or Refresh All button pressed?回答@Rory

Microsoft Documentation

+0

感谢JJC的回应。该代码非常适合在A列中对名称进行排序,但是,它不会在DATA REFRESH时自动执行此操作,并且列B:H中的所有数据也不会与名称排序。因此,基本上错误的名称旁边的数据。任何帮助将非常感激。 – DomsDad18

+0

@ DomsDad18,我编辑了我的答案,以解决您指出的排序问题。我还添加了一些代码,使其在刷新数据连接后自动运行。 – JJC