Execution code to repeat a macro

Hernan_g_f

New Member
Joined
Jul 26, 2022
Messages
25
Office Version
  1. 365
Platform
  1. Windows
Hello friends,

I have a macro that I need to run between 10 - 25 times. Is there a command or code to repeat the macro automatically "n" times ?

Thanks in advance,
Hernán
 
Something like this maybe?

VBA Code:
Sub Perhaps_This()
    Dim i As Long
    For i = 0 To 5  '<~~ inclusive of zero, the total number of times to repeat the code
        
        '~~ Your code to repeat goes here
    
    Next i
End Sub
 
Upvote 0
You could also keep the original macro code in a separate procedure (macro), and create a new one where you call the other one.

For example, if your original macro is called "Macro1", you could create a new macro like this that calls and runs it however many times you like:
VBA Code:
Sub Macro2()
    Dim n as Long
    For i=1 to 25
        Call Macro1
    Next i
End Sub

The advantage to this is you do not have to change/update your original macro, which may be helpful if you also use it elsewhere, or sometimes want to run it once manually (without having to update your code every time).

Or, if you don't want to have to change the code at all (ever), and instead want to prompt the user for how many times to run the code at run-time, you could ask for a input at run-time like this:
VBA Code:
Sub Macro2()

    Dim i As Long
    Dim n As Long
    
    On Error GoTo err_chk
    
    n = InputBox("How many times do you want to run the code?")
    If n > 0 Then
        For i = 1 To n
            Call Macro1
        Next i
    Else
        MsgBox "You have not entered a valid numeric value!", vbOKOnly, "TRY AGAIN!"
    End If
    
    Exit Sub
    
    
err_chk:
    MsgBox "You have not entered a valid numeric value!", vbOKOnly, "TRY AGAIN!"

End Sub
 
Upvote 0
Solution

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