VBA to apply macro to selected sheets

Daystep

New Member
Joined
Oct 17, 2017
Messages
2
Hello,

I've been dabbling with macros recently, but have not found a way to apply macros to selected sheets in the workbook. The macro I have works flawlessly on the active sheet, it applies the proper page breaks and if a certain section is completely hidden it won't print the page.

Below is the macro, and I am trying to get it to apply to any selected sheets in the workbook.

Code:
Sub ChangePrintArea()

Dim pb, i As Integer


pb = Array(31, 61, 109, 145, 193)




With ActiveSheet


    .ResetAllPageBreaks ' remove all page breaks from
    .PageSetup.PrintArea = "$A$1:$AI$192"
    .PageSetup.FitToPagesWide = 1
    .PageSetup.Zoom = 69
    For i = LBound(pb) To UBound(pb)
   
        If .Rows(pb(i)).Hidden = True Then
        .HPageBreaks.Add Before:=.Cells(749, 1)
        Else
        .HPageBreaks.Add Before:=.Cells(pb(i), 1)
        .HPageBreaks.Add Before:=.Cells(749, 1)
       
        End If
    Next i
End With
End Sub

Thanks,
 

Excel Facts

Convert text numbers to real numbers
Select a column containing text numbers. Press Alt+D E F to quickly convert text to numbers. Faster than "Convert to Number"
Your problem is that there can only be one ActiveSheet at a time. No matter how sheets you select, only one if them will be active. Therefore, you probably need to perform a loop through each of the selected worksheets. Something like:

For each ws In ActiveWindow.SelectedSheets
....your code....
Next ws
 
Upvote 0

Forum statistics

Threads
1,214,986
Messages
6,122,611
Members
449,090
Latest member
vivek chauhan

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top