Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting zoom without select in Excel VBA

Is it possible to set up zoom level based on screen resolution without Select?

I have followed the code:

Sheets(1).Range("A1:AC1").Select
ActiveWindow.Zoom = True

taken from https://stackoverflow.com/a/19439177/1903793

Desired code would be something like:

Range("A1:AC1").Width.Zoom=True

Update. Why do I want to avoid Select?

  1. My sheet has hidden columns based on user settings. So some columns of the range A1:AC1 are hidden. I cannot select single column because this particular column may be hidden.
  2. Selection triggers events. Of course I can disable the events but disabling the events has some side effects which I want to avoid.
like image 257
Przemyslaw Remin Avatar asked Sep 07 '25 23:09

Przemyslaw Remin


1 Answers

Just measure the current window width and the range's width. Then you can use those values to set a scaling ratio. Note - this needs some additional validation and error handling, but it should give the basic idea.

Private Sub ZoomToRange(target As Range)
    'Get the window from the target range.
    Dim wnd As Window
    Set wnd = ActiveWindow

    'Find out what you need to scale to.
    Dim scaling As Long
    scaling = 100 * wnd.Width / target.Width
    'Limit to max and min zoom level.

    If scaling > 400 Then
        wnd.Zoom = 400
    ElseIf scaling < 10 Then
        wnd.Zoom = 10
    Else
        wnd.Zoom = scaling
    End If
    'Scroll to the upper left cell
    target.Cells(1, 1).Activate
End Sub
like image 176
Comintern Avatar answered Sep 10 '25 14:09

Comintern