Shloime
Board Regular
- Joined
- Oct 25, 2023
- Messages
- 60
- Office Version
- 365
- 2021
- 2019
- 2016
- Platform
- Windows
I have Excel files with many macros that retrieve or write data across different sheets. I want a reliable way to set variables for specific columns so that:
This approach works if "First Name" is moved to a different column. However, I would need to set these variables in each module or sub, so any change in column title (like "First Name" to "Names") means updating each instance manually.
To simplify this, I created a single module with constants for each header row and a function to retrieve the column numbers based on column names:
the in every Sub i declare the variables i need to use is that like:
Is there a more efficient way to manage the column references, making them easier to maintain and update across multiple modules?
- They automatically adjust if columns are added, removed, or rearranged.
- I can quickly update them if I change a column title (e.g., from "Names" to "First Name").
- The column variables are accessible across all modules/subs, so I don’t have to redefine them repeatedly.
VBA Code:
S1colFN = Application.Match("First Name", S1.Rows(SHr), 0)
This approach works if "First Name" is moved to a different column. However, I would need to set these variables in each module or sub, so any change in column title (like "First Name" to "Names") means updating each instance manually.
To simplify this, I created a single module with constants for each header row and a function to retrieve the column numbers based on column names:
VBA Code:
Public Const NMHDr As Integer = 10
Function ColVar(CV As String) As Integer
Dim cn As Integer
Select Case CV
Case "NMcolHO"
cn = Application.Match("Holiday", NM.Rows(NMHDr), 0)
Case "NMcolID"
cn = Application.Match("ID", NM.Rows(NMHDr), 0)
Case "NMcolSN"
cn = Application.Match("Surname", NM.Rows(NMHDr), 0)
End Select
ColVar = cn
End Function
VBA Code:
Dim NMcolID as integer
NMcolID=colvar("NMcolID")