I'm trying to figure out a better way to format cells using VBA. I'm trying to replace an Option button from Excel Forms Control (it works fine but is quite ugly. It looks like old W95). I'm not using activeX as I can't rely that every single user would be able to open this workbook if I use activex.
So, I was trying to use some VBA to format a cell like a pressed button. It was supposed to be easy with a SUB to format as a pressed and another to unpressed. But this code is running for not less than 13 seconds! It's not feasible.
I've made some research and found other topics, inclusing "VBA Code optimization"
VBA code optimization
Other topics:
slow cell formatting using vba? But my case is just borders and cell color
Extremely slow VBA code when formatting cells From where I've got the optimatizaion code
Here is the code
Sub BtnSelect()
Dim t
t = Timer
With Selection
.Borders(xlDiagonalDown).LineStyle = xlNone
.Borders(xlDiagonalUp).LineStyle = xlNone
With .Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.Color = -1740185
.TintAndShade = 0
.Weight = xlMedium
End With
With .Borders(xlEdgeTop)
.LineStyle = xlContinuous
.Color = -1740185
.TintAndShade = 0
.Weight = xlMedium
End With
With .Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.Color = -736322
.TintAndShade = 0
.Weight = xlMedium
End With
With .Borders(xlEdgeRight)
.LineStyle = xlContinuous
.Color = -736322
.TintAndShade = 0
.Weight = xlMedium
End With
.Borders(xlInsideVertical).LineStyle = xlNone
.Borders(xlInsideHorizontal).LineStyle = xlNone
With .Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 16576494
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End With
Debug.Print Timer - t
End Sub
What am I doing wrong? It's kinda stupid this simple operation takes so long. Thank you very much!
This runs in <0.02 sec for me
Sub BtnSelect()
Dim t
t = Timer
With Selection
With .Borders()
.LineStyle = xlContinuous
.TintAndShade = 0
.Weight = xlMedium
End With
.Borders(xlDiagonalDown).LineStyle = xlNone
.Borders(xlDiagonalUp).LineStyle = xlNone
.Borders(xlInsideVertical).LineStyle = xlNone
.Borders(xlInsideHorizontal).LineStyle = xlNone
.Borders(xlEdgeLeft).Color = -1740185
.Borders(xlEdgeTop).Color = -1740185
.Borders(xlEdgeBottom).Color = -736322
.Borders(xlEdgeRight).Color = -736322
.Interior.Color = 16576494
End With
Debug.Print Timer - t
End Sub