Search code examples
excelvbazooming

VBA code that changes zoom level based on text/object in sheet?


All,

I've been looking for VBA code that achieves the following:

  1. Sets zoom to 80% for worksheets that contain a certain key word
  2. Sets zoom to 60% for worksheets that contain a picture
  3. Sets zoom to 85% for worksheets that contain a different key word

Here is the code that I have been trying to manipulate to suit this particular challenge, with my non-code comments indicating what I'd like to change:

Sub ZoomSheets() 
   Dim ws As Worksheet  
    Application.ScreenUpdating = False 
    For Each ws *with a picture* In Worksheets 
        ws.Activate
        ActiveWindow.Zoom = 60
    Next
    For Each ws *that contains X text* In Worksheets 
        ws.Activate
        ActiveWindow.Zoom = 80
    Next
    For Each ws *that contains Y text* In Worksheets 
        ws.Activate
        ActiveWindow.Zoom = 85
    Next
    Application.ScreenUpdating = True
    End Sub

For a certain deliverable at my job, the manager prefers certain sheets within an excel workbook to be at different zoom levels depending on what the sheet contains: 60% if there is a picture, 85% if it says "Y" at the top and 80% if it says "X" at the top. I've been able to find VBA code that sets a uniform zoom across all sheets, but I am looking for help writing code that is a little more flexible and allows me to vary the zoom depending on what the sheet contains.

Thank you!


Solution

  • Sub ZoomSheets()
    
        Application.ScreenUpdating = False
    
        Dim ws As Worksheet
        Dim checkRng As String: checkRng = "A1:ZZ999"
        Dim picture As Variant
        For Each ws In ThisWorkbook.Worksheets
        
            With ws.Range(checkRng)
                If Not .Find("epic", LookIn:=xlValues) Is Nothing Then
                    ws.Activate
                    ActiveWindow.Zoom = 90
                ElseIf Not .Find("poggers", LookIn:=xlValues) Is Nothing Then
                    ws.Activate
                    ActiveWindow.Zoom = 80
                Else
                    For Each picture In ws.Pictures
                        If picture.Name Like "*Picture*" Then
                            ws.Activate
                            ActiveWindow.Zoom = 70
                            Exit For
                        End If
                    Next
                End If
            End With
        
        Next ws
    
        Application.ScreenUpdating = True
    
    End Sub