I hope you're doing well. I am reaching out to the Stack Overflow community as I am currently experiencing beginner problem in programming in VBA in Excel. I am indeed trying to shorten and harmonize excels processes in my company.
CONTEXT
Among other commands, I am trying to program a macro to Center across selection (that can be pretty useful and which is a pain to right click go to Format etc.). I found the code online and somehow it works to some extent.
PROBLEM
Step 1
I select some cells. I run the macro (see code below). It centers across selection.
Step 2
I select a greater range of cells. It still center across selection.
Step 3
I select a smaller range of cells. It doesn't center across selection. It keeps the widest range used on this particular set of cells.
WHAT I HAVE TRIED SO FAR
I tried using the Selection.ClearFormats command ; didn't work (maybe not used well).
CODE
Sub center_across_selection()
'
' center_across_selection Macro
'
' Touche de raccourci du clavier: Ctrl+Shift+M
'
With Selection
If .HorizontalAlignment = xlCenterAcrossSelection Then
.HorizontalAlignment = xlGeneral
'converts regular text to centered across selection
Else
Selection.HorizontalAlignment = xlCenterAcrossSelection
End If
End With
End Sub
Thank you for your help!