I am still new to Excel VBA and albeit I can get most things to work I am sure there is a better way to do it.
In this example I have created a function to sort my workbook sheets based upon a table column header.
What I really wanted to do was create a function where I could pass the sheet name, table name and column header
into the function, but I just could not get the range correct for the sort key, so I ended up creating a function
where I just passed the sheet name down and used an if statement for all my sheets in the workbook.
The problem with this is I can only ever sort the using a set column in my sheets and if I add another table, I will have to remember
to change the function.
Can anyone help me to reach my goal and get rid of the if statements?
Function SortTable(sheet)
' ----------------------------------------------------------------
' Procedure Name: SortTable
' Purpose: Sort Tables on the first column
' Procedure Kind: Function
' Procedure Access: Public
' Parameter sheet (): Name of the worksheet
' Author: Melvyn
' Date: 22/11/2020
' ----------------------------------------------------------------
Dim ws As Worksheet
Dim tbl As ListObject
Dim rng As Range
Set ws = Sheets(sheet)
ws.Activate
If sheet = "Organisation" Then
Set tbl = ws.ListObjects("tblOrganisation")
Set rng = Range("tblOrganisation[Id]")
ElseIf sheet = "OrgDocument" Then
Set tbl = ws.ListObjects("tblOrgDocument")
Set rng = Range("tblOrgDocument[Id]")
ElseIf sheet = "OrgService" Then
Set tbl = ws.ListObjects("tblOrgService")
Set rng = Range("tblOrgService[Id]")
ElseIf sheet = "TargetUser" Then
Set tbl = ws.ListObjects("tblTargetUser")
Set rng = Range("tblTargetUser[TargetUser]")
ElseIf sheet = "Gender" Then
Set tbl = ws.ListObjects("tblGender")
Set rng = Range("tblGender[Gender]")
ElseIf sheet = "Service" Then
Set tbl = ws.ListObjects("tblService")
Set rng = Range("tblService[Service]")
End If
With tbl.Sort
.SortFields.Clear
.SortFields.Add key:=rng, SortOn:=xlSortOnValues, Order:=xlAscending
.Header = xlYes
.Apply
End With
End Function
Thanks
Bookmarks