VBA to Change Absolute and Relative Cell References
In response to a newsgroup question, I recently referenced a VBA procedure at Ozgrid.com that shows how to change relative and absolute row - column references. I thought I might document some slightly simplified versions for my own use:
To convert all formulas within a stated range to absolute references:
Sub All_Absolute()
Dim Rng As Range
Set Rng = Range("A1:A5")
Rng.SpecialCells(xlCellTypeFormulas) = Application.ConvertFormula(Rng.Formula, _
FromReferenceStyle:=xlA1, ToReferenceStyle:=xlA1, ToAbsolute:=xlAbsolute)
End Sub
To convert all formulas within a stated range to relative references:
Sub All_Relative()
Dim Rng As Range
Set Rng = Range("A1:A5")
Rng.SpecialCells(xlCellTypeFormulas) = Application.ConvertFormula(Rng.Formula, _
FromReferenceStyle:=xlA1, ToReferenceStyle:=xlA1, ToAbsolute:=xlRelative)
End Sub
To convert all formulas within a stated range to relative row / absolute column references:
Sub Relative_Row_Absolute_Column()
Dim Rng As Range
Set Rng = Range("A1:A5")
Rng.SpecialCells(xlCellTypeFormulas) = Application.ConvertFormula(Rng.Formula, _
FromReferenceStyle:=xlA1, ToReferenceStyle:=xlA1, ToAbsolute:=xlRelRowAbsColumn)
End Sub
To convert all formulas within a stated range to relative column / absolute row references:
Sub Relative_Column_Absolute_Row()
Dim Rng As Range
Set Rng = Range("A1:A5")
Rng.SpecialCells(xlCellTypeFormulas) = Application.ConvertFormula(Rng.Formula, _
FromReferenceStyle:=xlA1, ToReferenceStyle:=xlA1, ToAbsolute:=xlAbsRowRelColumn)
End Sub
I would consider collapsing the four macros into a single subroutine that would be called from one’s own macro. Here is the subroutine…
Sub SetReferenceStyle(RefStyle As XlReferenceType)
Dim Cell As Range
For Each Cell In Selection
If Cell.HasFormula Then Cell.Formula = _
Application.ConvertFormula(Cell.Formula, xlA1, xlA1, RefStyle)
Next Cell
End Sub
and you would call it like this…
SetReferenceStyle xlRelRowAbsColumn
where the argument choices are (use either the number or the predefined constant, not both)...
1—xlAbsolute
2—xlAbsRowRelColumn
3—xlRelRowAbsColumn
4—xlRelative
Because I declared RefStyle as XlReferenceType, VB’s Intellisense will present these to you in a selectable drop down box when calling the subroutine.