Re: Freeze Panes VBA Without Select
Dave,
I know my code uses select and activate, because that's the only way to do it. The code I posted was simply showing how I've chosen to work with the problem. If there is a better way, I would be very glad to learn, becaused I have a couple of apps out there that are using this method, and I don't feel very confident in it.
The question however is completely sensible. You start programming in VBA, and you learn that you don't need to select cells to do things, and suddenly you can't figure out how the heck to freeze panes at a certain point without selecting. No false premises there, IMO.
Hooking the freezepanes into the worksheet_activate event, while relatively reliable, would be _really_ annoying, because the screen would twich every time you activate a sheet. In the best case scenario, where you would record the previous selection, scroll status, and then toggle them back, the screen would still twitch every time you activate a sheet. With a lot of data, and especially with some shapes (such as charts) mixed in, this can look really bad, as the redrawing time can be perceivable. Or if the user has selected the entire sheet or other large amount of data, and changes sheets temporarily and goes back. On my computer selecting large filled ranges can sometimes freeze Excel for 3-10 seconds.
Or if the user doesn't like the freezepanes and turns them off, then goes to check another sheet and coming back, bam! The old settings are back. Not to mention the fact that it is completely unnecessary to redo this at every sheet activation, once you freeze the panes while you are running other code anyway, like OP, you don't need to mess with it again until the next time you turn them off.
The event handler I tried to test this looks like this:
Private Sub Worksheet_Activate()
Dim rngSelection As Range
Dim lngScrollRow As Long
Dim lngScrollCol As Long
Set rngSelection = Selection
lngScrollRow = ActiveWindow.ScrollRow
lngScrollCol = ActiveWindow.ScrollColumn
If ActiveWindow.FreezePanes Then
ActiveWindow.FreezePanes = False
End If
Range("C6").Select
ActiveWindow.FreezePanes = True
rngSelection.Select
If ActiveWindow.ScrollRow <> lngScrollRow Then
ActiveWindow.ScrollRow = lngScrollRow
End If
If ActiveWindow.ScrollColumn <> lngScrollCol Then
ActiveWindow.ScrollColumn = lngScrollCol
End If
End Sub
Display More
Peruse it at your will, but you should know that it needs some failguards for if the selection is not a range.