简体   繁体   中英

How to run an Excel macro on a specific sheet?

Let's say I have 10 sheets in an Excel workbook and Sheet2 through Sheet10 are uniquely formatted.

Let's say I recorded 9 unique macros.
Sheet1 is a central location to house nine buttons. One button for each recorded macro so that when the user goes to sheet 1 and clicks a button called "sheet 2" it will run the macro for sheet 2 against sheet 2, even if the user is on the active sheet 1. Or if the user clicks the button called "sheet 10" it runs the recorded macro for sheet 10 against sheet 10, etc.

Here is a simplified version of one of the macros.

Sub Sheet2()
'
' Sheet2 Macro
'

'
End Sub

Sub Sheet2Macro()
'
' Sheet2Macro Macro
'

'
    Range("A2:C2").Select
    Selection.AutoFill Destination:=Range("A2:C10"), Type:=xlFillDefault
    Range("A2:C10").Select
End Sub

I found this code online that I added at the top and it runs to success but only on the active sheet:

Dim WkSheets As Variant, SheetName As Variant, ws As Worksheet

'** SET The Sheet Names - MUST Reflect Each Sheet Name Exactly!
WkSheets = Array("Sheet 2")
    
For Each SheetName In WkSheets

    'MsgBox SheetName
    
    For Each ws In ActiveWorkbook.Worksheets
        If ws.Name = SheetName Then
            
            'Your Code Here

If you are using 9 unique macros that you recorded, those will be set specifically for the sheets they are recorded from, and then you simply tie in the code to be called when the button for each specific one is clicked. As stated before it would be helpful to know if they were Form Controls or ActiveX Controls, but you would change the text in your button to say "Sheet 2 Button" for instance, and the code tied to that button would be something along the lines of

Private Sub Sheet2Button_Click()
    Call Sheet2Macro
End Sub

So from there when you click the button that says Sheet 2 Button, it will call Sheet2Macro and that macro was recorded on Sheet2 so will run for Sheet2 no matter where the button is stored. Hopefully that makes sense.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM