I am having a little issue with my excel spreadsheet, I am hoping someone can help. I have Names starting in Cell=A7 that go to A177. All the other information are in Columns (B:H). Ideally I would like to run the code after I hit a Data Refresh. I am using this sheet so I can lookup information for another sheet, hence why it needs to be in Alphabetical Order A-Z. Information is from a web query.
Asked
Active
Viewed 2,570 times
-1
-
1record macro: refresh data -> sort it like you want it to be -> stop recording... use the macro to repeat this action :D – Dirk Reichel Nov 08 '15 at 15:52
1 Answers
0
EDIT:
Add the following code to a standard Module. See the edit in the code to make sure that it properly sorts all of your columns together as expected.
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
Then create a class module and insert the following code:
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
Note that Auto_Open()
must be ran first in order for AutoSort()
to work properly. This should happen any time you open the workbook.
The code is drawing heavily upon the work of others, namely:
How to call macro after Refresh or Refresh All button pressed? answered by @Rory
-
Thanks JJC for responding. The code works great for sorting the names in column A, however, it doesn't automatically do it upon a DATA REFRESH, and also all the data in Columns B:H does not sort with the names. So basically the data next to the names in wrong. Any help would be much appreciated. – DomsDad18 Nov 09 '15 at 14:32
-
@DomsDad18, I edited my answer to fix the sorting problem you pointed out. I also added some code to make it run automatically after data connections are refreshed. – JJC Nov 11 '15 at 02:23