I have list of worksheets, table names, column names and format details in columns B, C, D and E in a worksheet and I want the VBA macro to loop through this list to apply formatting in the respective worksheet's table/name range columns Or All Columns.
please see the below table and the code I have so far.. can someone help with amending the below code to make it work as per my expectation
| # | Worksheet Name | Table Name / Range Name | Column Names | Format |
|---|---|---|---|---|
| 1 | Philip | Philip_Test3 | Commentary, Date, Time Stamp, Region | CustomFormat |
| 2 | Edward | Edward_Test8 | City, Region, Template Name | CustomFormat |
| 3 | Jessica | Jessica_Test2 | Date, Time Stamp, Region | CustomFormat1 |
| 4 | Tony | Tony_Test1 | Commentary, Time Stamp, Region, Template Name | CustomFormat |
| 4 | Roger | Roger_TestNew | All Columns | CustomFormat1 |
Option Explicit
Sub FormatMultipleRanges()
Dim Cell As Range
Dim nm As Name
Dim sht As Worksheet
Set sht = ThisWorkbook.ActiveSheet
Dim myRange As Range
Set myRange = sht.Range("D2:D9")
Dim FormatRng As Range
Set FormatRng = sht.Range("E2:E9")
For Each sht In Worksheets
If Not IsError(Application.Match(sht.Name, Range("B2:B9"), 0)) Then
For Each nm In ActiveWorkbook.Names
If Not IsError(Application.Match(nm.RefersToRange.Parent.Name, Range("C2:C9"), 0)) Then
For Each Cell In myRange
CustomFormat (myRange)
Next myRange
'
End If
Next
End Sub
formatting function
public function CustomFormat(rng as excel.range)
rng.VerticalAlignment = xlTop
rng.WrapText = True
end function
public function CustomFormat1(rng as excel.range)
rng.VerticalAlignment = xlCenter
rng.WrapText = True
end function
Microsoft documentation:
Update:
Update2: