I am using this VBA function, and right now it works fine as the format of my spreadsheet has not changed. But I will be adapting it for another use, and the order is likely going to be changing a bit more often. The table header names that I need for this function will not change their names though. My whole spreadsheet equations already uses structured references, but I am struggling to wrap my head around how exactly I eliminate the remnants of the explicit references to the column position in the VBA code.
The row that states If data(i, 2).Value = expNum Then and
If data(i, 14).Value <> Empty Then
curEnergy = data(i, 14).Value`
Are the ones in question. Column 2 corresponds to a column named "Exp #", and Column 14 corresponds to a column name "G (kcal/mol)" I've attached the full function below, just in case there are critical pieces in other sections that I'm not aware of. I would like to replace those references to 2 and 14 with the structured reference or something robust to withstand reordering of column positions.
Function BoltzmannEnergy(expNum As String) As Double
Application.Volatile
Worksheets("Raw Values").Activate
Dim data As Range, curCell As Range
Dim numRows As Integer, arrayCount As Integer, arraySize As Integer
Dim energies() As Double, curEnergy As Double, minEnergy As Double, RT As Double, BoltzTop As Double, BoltzBtm As Double
Dim expFound As Boolean
Const T As Double = 298
Const R As Double = 0.001985
RT = R * T
BoltzTop = 0
BoltzBtm = 0
expFound = False
arraySize = 5
minEnergy = 0
ReDim energies(0 To arraySize)
Set data = Range("RawValues")
arrayCount = 0
numRows = data.Rows.Count
For i = 1 To numRows
If data(i, 2).Value = expNum Then
If arrayCount = UBound(energies) - 1 Then
ReDim Preserve energies(0 To arrayCount + arraySize + 1)
End If
expFound = True
If data(i, 14).Value <> Empty Then
curEnergy = data(i, 14).Value
If curEnergy <> 0 Then
If curEnergy < minEnergy Then
minEnergy = curEnergy
End If
energies(arrayCount) = curEnergy
arrayCount = arrayCount + 1
End If
End If
ElseIf expFound = True Then
Exit For
End If
Next i
For i = 0 To arrayCount - 1
BoltzTop = BoltzTop + energies(i) * Exp(-(energies(i) - minEnergy) / RT)
BoltzBtm = BoltzBtm + Exp(-(energies(i) - minEnergy) / RT)
Next i
BoltzmannEnergy = BoltzTop / BoltzBtm
End Function
Range("RawValues").rows(1).offset(-1,0).address()will give you the range with the headers: you can use Derek's approach to find the relevant column positions.