Forum Discussion
Excel Sort function on the active range
If you want to sort the data in place, you could use VBA code to sort the table when the workbook is opened, and if desired also when you switch to the relevant sheet from another sheet in the workbook.
(Sorting automatically as data are being added/edited is not a good idea, it would look very confusing.)
To do so:
1) Press Alt+F11 to activate the Visual Basic Editor.
Select Insert > Module.
Copy the following code into the module:
Sub SortData()
With Worksheets("Sheet1")
.Range("A1").CurrentRegion.Sort Key1:=.Range("J1"), Header:=xlYes
End With
End Sub
Change the name of the sheet to the one containing the table, and change A1 and J1 if the table does not start in A1.
2) Double-click ThisWorkbook under Microsoft Excel Objects in the Project Explorer pane on the left.
Copy the following code into the ThisWorkbook module:
Private Sub Workbook_Open()
Call SortData
End Sub
This will sort the data when the workbook is opened.
3) Double-click the relevant worksheet in the Project Explorer.
Copy the following code into the worksheet module:
Private Sub Worksheet_Activate()
Call SortData
End Sub
This will sort the data when you switch to the worksheet from another sheet in the same workbook.
4) Switch back to Excel.
Save the workbook as a macro-enabled workbook (.xlsm).
Make sure that you allow macros when you open the workbook.
- FrankWitselMar 01, 2021Copper ContributorDag Hans, dankjewel voor je uitgebreid antwoord en alhoewel ik Visual Basic nog nooit heb geprobeerd ga ik jouw advies wel proberen. Ik begrijp ook je kritiek, maar maak je geen zorgen, de toegevoegde regels zijn na invoering in 95% van de gevallen de regels die altijd onderaan staan. Het is een voorraadoverzicht met LOT en THT gegevens die ik in het overzicht wil bewaren maar die na uitlevering steeds verder in waarde dalen en die wil ik zoveel mogelijk naar boven verschuiven totdat ze op '0' staan en uit beeld zijn en onderaan alleen de rijen tonen waar nog voorraad van staat. Gr. Frank PS of heb jij een beter idee...? en dan heb ik het niet over voorraadboekhouding van Exact of zo, maar een betere oplossing in Excel.