Activewindow zoom excel vba

Return to VBA Code Examples

ActiveWindow.Zoom

You can use VBA to change the Zoom of a worksheet. Here’s code to change the Zoom of the ActiveWindow to 50%:

ActiveWindow.Zoom = 50

Change Zoom on all Worksheets

You can also loop through all the worksheets in your workbook to set a standard Zoom. The following Macro will set the Zoom for all worksheets to 50%:

Sub ZoomAll()

  Dim ws As Worksheet

  Application.ScreenUpdating = False

  For Each ws In Worksheets
    ws.Activate
    ActiveWindow.Zoom = 50
  Next

  Application.ScreenUpdating = True

End Sub

Zoom Zoom

And finally a magically growing worksheet. The following macro will loop through the Zooms for Sheet1, going from 10% to 200%, incrementing by 10%, pausing a second between changes, and then it will restore Sheet1 back to it’s original state.

Sub ZoomZoom()
Dim x As Integer 'variable for loop
Dim OriginalZoom As Integer 'variable for original zoom

Sheet1.Activate 'let's work with sheet1

OriginalZoom = ActiveWindow.Zoom 'get current zoom

'loop through zoom 10 to 200 by 10
    For x = 1 To 20
        ActiveWindow.Zoom = x * 10
        Application.Wait Now + TimeValue("00:00:01")
    Next x
    
'restore original zoom
ActiveWindow.Zoom = OriginalZoom

End Sub

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro – A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

alt text

Learn More!

Excel has zoom settings for worksheets, UserForms and print settings.  Each of these serves different purposes and used at different points, but they can all be controlled by VBA.

Worksheet zoom settings

The worksheet zoom setting in Excel will always be an integer.  If the value set by VBA contains decimal places it will be rounded down to the nearest whole number.

'Change worksheet zoom setting for the active window
ActiveWindow.Zoom = 56
'Change worksheet zoom setting for any open window
Windows("Book1.xlsx").Zoom = 56

The minimum and maximum zoom settings permitted are 10% and 400%.

Zoom to Selection

Excel contains a setting called Zoom to Selection, which is in the View Ribbon.

View Zoom To Selection

Clicking this button will automatically zoom the active worksheet to fit the selected cells.   This option is also available within the Zoom window.

Zoom settings Fit to Selection

The Zoom to Selection / Fit to Selection feature can be controlled with VBA, however it does require a range to be selected.  The code below selects Cells A1:J15, the and zooms the window to the size of those cells.

'Zoom to selection
Range("A1:J15").Select
ActiveWindow.Zoom = True

Transferring current zoom setting to a variable

The zoom setting can be assigned to a variable for use at a later point in the code.

'Setting variable to zoom setting of active window
Dim zoomSetting As Integer
zoomSetting = ActiveWindow.Zoom
'Setting variable to zoom setting of any named window 
Dim zoomSetting As Integer 
zoomSetting = Windows("Book1.xlsx").Zoom

Change the zoom functions of the mouse scroll wheel

Virtually every mouse has a scroll wheel, or similar scrolling feature.  By default the wheel will scroll up and down the page, but with Ctrl + mouse scroll will zoom into an Excel worksheet.  With VBA it is possible to reverse these settings when used within Excel.

'Zoom with souse scroll, scroll with Ctrl + mouse scroll
Application.RollZoom = True
'Zoom with Ctrl + mouse scroll, scroll with mouse scroll (default settings)
Application.RollZoom = False

The Zoom DialogBox

VBA can trigger the display of the Zoom window.

The value after the .Show is the default size selected in the window.  If that value is also a standard size, such as 200%, 100%, 75%, etc., that option will be highlighted automatically in the Zoom window.

'Display Zoom window include 150% as default selection
Application.Dialogs(xlDialogZoom).Show (150)

I do not believe it is possible to capture the requested value from the Zoom window, without changing the zoom setting.  Therefore, as a workaround, it is necessary assign the original value to a variable, change the zoom setting, record the new value, then revert to the original.

'Capture Zoom Setting from dialogBox

'Create variable to hold the zoom setting
Dim zoomSetting As Integer
zoomSetting = ActiveWindow.Zoom

'Open the zoom dialog box to change setting
Application.Dialogs(xlDialogZoom).Show (zoomSetting)

'Print Zoom Setting to the Immediate Window
Debug.Print ActiveWindow.Zoom

'Return the Zoom Setting to original state
ActiveWindow.Zoom = zoomSetting

Print Zoom

When printing a document there are different zoom settings available, which only apply to printed documents.

Zoom Settings - Page Setup

This setting is controlled by the following VBA examples.  Each example is applied to a worksheet called ZoomSettings, but could also be applied to the ActiveSheet.

'Set the zoom level
Worksheets("ZoomSettings").PageSetup.Zoom = 150
'Turn off the zoom level and fit to pages
Worksheets("ZoomSettings").PageSetup.Zoom = False
'Zoom to a specific number of pages
Worksheets("ZoomSettings").PageSetup.FitToPagesWide = 5
Worksheets("ZoomSettings").PageSetup.FitToPagesTall = 1

UserForm Zoom

The VBA UserForm also includes it’s own zoom setting.  Though, it’s not as useful as you might think, as it does to change the size of the form, just the items on the form.  To keep things in proportion, it is necessary to resize the form using the Height and Width properties.

'Settings below this size will change the proportions of the UserForm to 300%
Dim zoomSetting As Double
ZoomSetting = 300

'Display the UserForm
UserForm1.Show

'Change zoom setting of UserForm
UserForm1.Zoom = ZoomSetting

'Change Width & Height by same proportion as Zoom setting
UserForm1.Width = UserForm1.Width * ZoomSetting / 100
UserForm1.Height = UserForm1.Height * ZoomSetting / 100

The minimum and maximum permitted widths are 99 and 12287.5.

The minimum and maximum permitted heights are 28.5 and 12287.5.

If provided with a value outside the permitted range, VBA will automatically adjust the height and width UserFrom to be minimum or maximum.  This can result in UserForms which are not in the same proportions.


Headshot Round

About the author

Hey, I’m Mark, and I run Excel Off The Grid.

My parents tell me that at the age of 7 I declared I was going to become a qualified accountant. I was either psychic or had no imagination, as that is exactly what happened. However, it wasn’t until I was 35 that my journey really began.

In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a small number of simple tools, I could combine them together in different ways to automate nearly all my regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to other professionals in our training program so they too can spend less time at work (and more time with their children and doing the things they love).


Do you need help adapting this post to your needs?

I’m guessing the examples in this post don’t exactly match your situation. We all use Excel differently, so it’s impossible to write a post that will meet everybody’s needs. By taking the time to understand the techniques and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.

But, if you’re still struggling you should:

  1. Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
  2. Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
  3. Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people on these forums are generally giving their time for free. So take care to craft your question, make sure it’s clear and concise.  List all the things you’ve tried, and provide screenshots, code segments and example workbooks.
  4. Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.

What next?
Don’t go yet, there is plenty more to learn on Excel Off The Grid.  Check out the latest posts:

I have a VBA that will set the zoom level based on the screen resolution.
But its working only for ActiveWindow when you open workbook.
How can I add this across all worksheets in Excel?

Declare Function GetSystemMetrics32 Lib "user32" _
    Alias "GetSystemMetrics" (ByVal nIndex As Long) As Long

Public Sub ScreenRes()
    Dim lResWidth As Long
    Dim lResHeight As Long
    Dim sRes As String

    lResWidth = GetSystemMetrics32(0)
    lResHeight = GetSystemMetrics32(1)
    sRes = lResWidth & "x" & lResHeight
    Select Case sRes
        Case Is = "800x600"
            ActiveWindow.Zoom = 75
        Case Is = "1024x768"
            ActiveWindow.Zoom = 125
        Case Else
            ActiveWindow.Zoom = 100
    End Select
End Sub

I will call this module on the Workbook

Private Sub Workbook_Open()
ScreenRes
End Sub

Community's user avatar

asked Sep 27, 2016 at 3:58

Manu's user avatar

1

building on @Jeeped answer you could place in ThisWorkbook code pane the following code:

Declare Function GetSystemMetrics32 Lib "user32" _
    Alias "GetSystemMetrics" (ByVal nIndex As Long) As Long

Option Explicit

Private Sub Workbook_Open()
    With Worksheets
        .Select
        ActiveWindow.zoom = ScreenResToZoom
    End With
End Sub

Public Function ScreenResToZoom() As Long
    Select Case GetSystemMetrics32(0) & "x" & GetSystemMetrics32(1)
        Case Is = "800x600"
            ScreenResToZoom = 75
        Case Is = "1024x768"
            ScreenResToZoom = 125
        Case Else
            ScreenResToZoom = 100
    End Select
End Function

answered Sep 27, 2016 at 13:54

user3598756's user avatar

user3598756user3598756

28.8k4 gold badges17 silver badges28 bronze badges

4

ActiveWindow.Zoom

Вы можете использовать VBA для изменения масштаба рабочего листа. Вот код для изменения масштаба ActiveWindow на 50%:

Изменить масштаб на всех листах

Вы также можете просмотреть все листы в своей книге, чтобы установить стандартное масштабирование. Следующий макрос устанавливает масштаб для всех листов на 50%:

123456789101112131415161718192021 Дополнительный ZoomAll ()Dim ws как рабочий листApplication.ScreenUpdating = FalseДля каждого ws в листахws.ActivateActiveWindow.Zoom = 50СледующийApplication.ScreenUpdating = TrueКонец подписки

Zoom Zoom

И, наконец, волшебно растущий рабочий лист. Следующий макрос будет циклически перебирать Zooms для Sheet1, переходя от 10% до 200%, увеличиваясь на 10%, делая паузу между изменениями в секунду, а затем он вернет Sheet1 в исходное состояние.

1234567891011121314151617181920212223242526272829303132333435363738 Дополнительное масштабирование ()Переменная Dim x As Integer для циклаПеременная Dim OriginalZoom As Integer для исходного масштабированияSheet1.Activate ‘давайте работать с Sheet1OriginalZoom = ActiveWindow.Zoom ‘получить текущий масштаб’циклическое увеличение от 10 до 200 на 10Для x = от 1 до 20ActiveWindow.Zoom = x * 10Application.Wait Now + TimeValue («00:00:01»)Далее x’восстановить исходный масштабActiveWindow.Zoom = OriginalZoomКонец подписки

Вы поможете развитию сайта, поделившись страницей с друзьями

You can use VBA to change the Zoom of a worksheet. Here’s code to change the Zoom of the ActiveWindow to 50%:

ActiveWindow.Zoom = 50

You can also loop through all the worksheets in your workbook to set a standard Zoom. The following [gs macro] will set the Zoom for all worksheets to 50%:

Sub ZoomAll()

Dim ws As Worksheet
Application.ScreenUpdating = False
For Each ws In Worksheets
ws.Activate
ActiveWindow.Zoom = 50
Next
Application.ScreenUpdating = True
End Sub

And finally a magically growing worksheet. The following [gs macro] will loop through the Zooms for Sheet1, going from 10% to 200%, incrementing by 10%, pausing a second between changes, and then it will restore Sheet1 back to it’s original state.

Sub ZoomZoom()

Dim x As Integer 'variable for loop
Dim OriginalZoom As Integer 'variable for original zoom
Sheet1.Activate 'let's work with sheet1
OriginalZoom = ActiveWindow.Zoom 'get current zoom
'loop through zoom 10 to 200 by 10
For x = 1 To 20
ActiveWindow.Zoom = x * 10
Application.Wait Now + TimeValue("00:00:01")
Next x
'restore original zoom
ActiveWindow.Zoom = OriginalZoom
End Sub

Понравилась статья? Поделить с друзьями:
  • Activesheet usedrange vba excel
  • Activesheet protect vba excel
  • Activesheet paste vba excel описание
  • Activesheet listobjects add excel
  • Activesheet cells vba excel