Vba excel как завершить макрос

Содержание

  1. Прерывание процедур и функций VBA
  2. Оператор Exit
  3. Оператор End
  4. Оператор Exit
  5. Синтаксис
  6. Замечания
  7. Пример
  8. См. также
  9. Поддержка и обратная связь
  10. Останов выполнения кода
  11. См. также
  12. Поддержка и обратная связь
  13. Excel VBA stop macro execution manually with Esc or Ctrl+Break
  14. The VBA Tutorials Blog
  15. VBA Stop Macro
  16. How to manually stop your macro
  17. Stopping an Infinite Loop Demo
  18. How to stop VBA code running?
  19. 7 Answers 7

Прерывание процедур и функций VBA

Иногда встречаются обстоятельства, при которых нет смысла продолжать выполнение процедуры или функции. VBA имеет операторы Exit и End, которые дают возможность либо завершать процедуру или функцию, либо останавливать всю программу.

Оператор Exit

Для того, чтобы процедура или функция прекратила выполнение, используется одна из двух доступных форм VBA-оператора Exit, в зависимости от того, необходимо ли завершить функцию или процедуру:

Перепишем немного листинг учебной программы, который использовался на позапрошлом уроке:

Здесь содержится код проверки того, была ли выбрана пользователем в окне ввода кнопка «Отмена». Если это так — программа выдает сообщение о том, что не был введен возраст, и прекращает выполнение кода оператором Exit Sub.

Оператор Exit Sub приводит к тому, что VBA немедленно прекращает выполнение кода процедуры. После выполнения этого оператора VBA прекращает выполнение текущей процедуры и возвращается к выполнению той процедуры или функции, которая вызвала процедуру, содержащую оператор Exit Sub.

Оператор End

Для полного завершения выполнения программы используется ключевое слово End в отдельной строке:

При выполнении этого оператора VBA прекращает все выполнение операторов процедуры и функции. Любые имеющиеся переменные перестают существовать и их значения теряются.

Т.к. программа полностью прерывается, необходимо перед оператором End выводить пользователю сообщение о том, что будет происходить и почему. В противном случае пользователи вашей процедуры могут не понять, почему процедура или программа, которую они используют, внезапно прекратила работу. Если программа перестанет выполняться вследствие какого-либо действия пользователя, такого как отмена окна ввода, без объяснения, пользователь процедуры может никогда не узнать, почему процедура заканчивается.

Также не следует забывать закрывать рабочие книги или выполнять другие сервисные работы перед выполнением оператора End, чтобы пользователю программы не приходилось доделывать незаконченные операции.

В начало страницы

В начало страницы

Источник

Оператор Exit

Выполняет выход из блока кода операторов Do…Loop, For…Next, Function, Sub или Property.

Синтаксис

Exit Do
Exit For
Exit Function
Exit Property
Exit Sub

Синтаксис оператора Exit состоит из следующих частей:

Statement Описание
Exit Do Предоставляет способ выхода из . Оператор Loop . Может использоваться только в пределах оператора Do. Loop. Exit Do передает управление оператору, следующему за оператором Loop. При использовании в пределах вложенных операторов Do. Loop, Exit Do передает управление в цикл, находящийся на один вложенный уровень выше, чем цикл, где выполняется оператор Exit Do.
Exit For Предоставляет способ выхода из цикла For. Его можно использовать только в for. Далее или Для каждого. Следующий цикл. Оператор Exit For передает управление оператору, следующему за оператором Next. При использовании во вложенных циклах For оператор Exit For передает управление циклу, находящемуся на один вложенный уровень выше цикла, где выполняется оператор Exit For.
Exit Function Немедленно завершает процедуруFunction, в которой она отображается. Выполнение продолжается с использованием оператора, который следует за оператором, выполнившим вызов процедуры Function.
Exit Property Немедленно завершает процедуру Property , в которой она отображается. Выполнение продолжается с использованием оператора, который следует за оператором, выполнившим вызов процедуры Property.
Exit Sub Немедленно завершает процедуру Sub , в которой она отображается. Выполнение продолжается с использованием оператора, который следует за оператором, выполнившим вызов процедуры Sub.

Замечания

Не следует путать операторы Exit иEnd. Оператор Exit не определяет завершение структуры.

Пример

В этом примере оператор Exit используется для выхода из цикла For. Next, процедур Do. Loop и Sub.

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Останов выполнения кода

Выполнение кода может остановиться по одной из следующих причин.

Происходит перехваченная ошибка во время выполнения и выбран элемент Останов при любой ошибке на вкладке Общие диалогового окна Параметры.

В коде обнаружен оператор Stop, выполняющий переключение в режим приостановки выполнения.

В коде обнаружен оператор End, выполняющий переключение в режим разработки.

Вы останавливаете выполнение вручную в данной точке.

Обнаружено контрольное выражение, которое вызывает останов при выполнении определенных условий.

Остановка выполнения вручную

Чтобы переключиться в режим приостановки, в меню Выполнить выберите Команду Break (CTRL+BREAK) или используйте сочетание клавиш на панели инструментов: .

Чтобы переключиться на время разработки, в меню Выполнить выберите Сброс проекта или используйте ярлык на панели инструментов: .

Продолжение выполнения после остановки приложения

  • В меню Отладка выберите команду Выполнить пошагово (F8), Шаг с обходом (SHIFT+F8), Шаг с выходом (CTRL+SHIFT+F8) или Выполнить до текущей позиции (CTRL+F8).

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Excel VBA stop macro execution manually with Esc or Ctrl+Break

The VBA Tutorials Blog

VBA Stop Macro

I accidentally created an infinite loop macro. How can I stop the macro from running?

This is a question I get asked quite often. Fortunately, the solution is easy to remember!

How to manually stop your macro

In VBA, you can stop your macro execution manually with the Esc key or by pressing Ctrl+Break.

Here are a couple alternatives if the first two keystroke options fail.

  1. If you’re running a macro that uses a lot of processing power, you may need to repeatedly press the Esc or Ctrl+Break keys before it’s finally recognized.
  2. If your keyboard has a function key, usually labeled Fn, you may have to hit Ctrl+Fn+Break to manually kill your macro.
  3. If none of these options work, your last resort is to kill the Excel application in its entirety. One way to do this is to press Ctrl+Alt+Delete, launch the Task Manager, click “Details” or “Processes” and scroll down until you find Excel. Once you find it, click it and select “End task.” This is certainly not the desired way to stop your macro because you’ll lose all your unsaved work!

Stopping an Infinite Loop Demo

Make powerful macros with our free VBA Developer Kit

It’s easy to copy and paste a macro like this, but it’s harder make one on your own. To help you make macros like this, we built a free VBA Developer Kit and wrote the Big Book of Excel VBA Macros full of hundreds of pre-built macros to help you master file I/O, arrays, strings and more — grab your free copy below.

Running the macro above creates an infinite loop. If you’re brave and you want to test out the keystrokes recommended above, now’s your chance.

Let’s try it! Run the macro and try pressing Esc or Ctrl+Break. You should get a dialog box that looks like this:

All you have to do is click “End” and your macro will stop.

That’s all for today’s tutorial. Short and sweet! When you’re ready to take your VBA to the next level, subscribe using the form below.

Ready to do more with VBA?
We put together a giant PDF with over 300 pre-built macros and we want you to have it for free. Enter your email address below and we’ll send you a copy along with our VBA Developer Kit, loaded with VBA tips, tricks and shortcuts.

Before we go, I want to let you know we designed a suite of VBA Cheat Sheets to make it easier for you to write better macros. We included over 200 tips and 140 macro examples so they have everything you need to know to become a better VBA programmer.

Источник

How to stop VBA code running?

Say I have a button embedded into my spreadsheet that launches some VBA function.

I’d like to have an opportunity to have some sort of a «cancel» button that would stop SomeVBASub execution at an arbitrary moment, and I’m not into involving Ctrl+Break here, ’cause I’d like to do it silently.

I guess this should be quite common issue, any ideas?

7 Answers 7

Add another button called «CancelButton» that sets a flag, and then check for that flag.

If you have long loops in the «stuff» then check for it there too and exit if it’s set. Use DoEvents inside long loops to ensure that the UI works.

How about Application.EnableCancelKey — Use the Esc button

Or, if you want to avoid the use of a global variable you could use the rarely used .Tag property of the userform:

what jamietre said, but

I do this a lot. A lot. 🙂

I have got used to using «DoEvents» more often, but still tend to set things running without really double checking a sure stop method.

Then, today, having done it again, I thought, «Well just wait for the end in 3 hours», and started paddling around in the ribbon. Earlier, I had noticed in the «View» section of the Ribbon a «Macros» pull down, and thought I have a look to see if I could see my interminable Macro running.

I now realise you can also get this up using Alt-F8.

Then I thought, well what if I «Step into» a different Macro, would that rescue me? It did 🙂 It also works if you step into your running Macro (but you still lose where you’re upto), unless you are a very lazy programmer like me and declare lots of «Global» variables, in which case the Global data is retained 🙂

Источник

Say I have a button embedded into my spreadsheet that launches some VBA function.

Private Sub CommandButton1_Click()
    SomeVBASub
End Sub

Private Sub SomeVBASub
    DoStuff
    DoAnotherStuff
    AndFinallyDothis
End Sub

I’d like to have an opportunity to have some sort of a «cancel» button that would stop SomeVBASub execution at an arbitrary moment, and I’m not into involving Ctrl+Break here, ’cause I’d like to do it silently.

I guess this should be quite common issue, any ideas?

Thanks.

asked Oct 20, 2010 at 16:02

Kirill Leontev's user avatar

Kirill LeontevKirill Leontev

10.6k7 gold badges43 silver badges49 bronze badges

Add another button called «CancelButton» that sets a flag, and then check for that flag.

If you have long loops in the «stuff» then check for it there too and exit if it’s set. Use DoEvents inside long loops to ensure that the UI works.

Bool Cancel
Private Sub CancelButton_OnClick()
    Cancel=True
End Sub
...
Private Sub SomeVBASub
    Cancel=False
    DoStuff
    If Cancel Then Exit Sub
    DoAnotherStuff
    If Cancel Then Exit Sub
    AndFinallyDothis
End Sub

answered Oct 20, 2010 at 16:10

Jamie Treworgy's user avatar

Jamie TreworgyJamie Treworgy

23.8k8 gold badges75 silver badges119 bronze badges

3

How about Application.EnableCancelKey — Use the Esc button

On Error GoTo handleCancel
Application.EnableCancelKey = xlErrorHandler
MsgBox "This may take a long time: press ESC to cancel"
For x = 1 To 1000000    ' Do something 1,000,000 times (long!)
    ' do something here
Next x

handleCancel:
If Err = 18 Then
    MsgBox "You cancelled"
End If

Snippet from http://msdn.microsoft.com/en-us/library/aa214566(office.11).aspx

answered Oct 20, 2010 at 16:17

Faheem's user avatar

Or, if you want to avoid the use of a global variable you could use the rarely used .Tag property of the userform:

Private Sub CommandButton1_Click()
    Me.CommandButton1.Enabled = False 'Disabling button so user cannot push it
                                      'multiple times
    Me.CommandButton1.caption = "Wait..." 'Jamie's suggestion
    Me.Tag = "Cancel"
End Sub

Private Sub SomeVBASub
    If LCase(UserForm1.Tag) = "cancel" Then
        GoTo StopProcess
    Else
        'DoStuff
    End If

Exit Sub
StopProcess:
    'Here you can do some steps to be able to cancel process adequately
    'i.e. setting collections to "Nothing" deleting some files...
End Sub

answered Mar 25, 2014 at 19:02

simpLE MAn's user avatar

simpLE MAnsimpLE MAn

1,56213 silver badges22 bronze badges

what jamietre said, but

Private Sub SomeVBASub
    Cancel=False
    DoStuff
    If not Cancel Then DoAnotherStuff
    If not Cancel Then AndFinallyDothis
End Sub

answered Oct 20, 2010 at 16:13

Beth's user avatar

BethBeth

9,5131 gold badge23 silver badges43 bronze badges

I do this a lot. A lot. :-)

I have got used to using «DoEvents» more often, but still tend to set things running without really double checking a sure stop method.

Then, today, having done it again, I thought, «Well just wait for the end in 3 hours», and started paddling around in the ribbon. Earlier, I had noticed in the «View» section of the Ribbon a «Macros» pull down, and thought I have a look to see if I could see my interminable Macro running….

I now realise you can also get this up using Alt-F8.

Then I thought, well what if I «Step into» a different Macro, would that rescue me? It did :-)
It also works if you step into your running Macro (but you still lose where you’re upto), unless you are a very lazy programmer like me and declare lots of «Global» variables, in which case the Global data is retained :-)

K

answered Jul 16, 2014 at 14:26

Kenson Gurney's user avatar

~ For those using custom input box

Private Sub CommandButton1_Click()

DoCmd.Close acForm, Me.Name
End

End Sub

answered Apr 1, 2015 at 10:51

Paul Clint's user avatar

Paul ClintPaul Clint

911 gold badge2 silver badges10 bronze badges

This is an old post, but given the title of this question, the END option should be described in more detail. This can be used to stop ALL PROCEDURES (not just the subroutine running). It can also be used within a function to stop other Subroutines (which I find useful for some add-ins I work with).

As Microsoft states:

Terminates execution immediately. Never required by itself but may be placed anywhere in a procedure to end code execution, close files opened with the Open statement, and to clear variables*. I noticed that the END method is not described in much detail. This can be used to stop ALL PROCEDURES (not just the subroutine running).

Here is an illustrative example:

Sub RunSomeMacros()

    Call FirstPart
    Call SecondPart

    'the below code will not be executed if user clicks yes during SecondPart.
    Call ThirdPart
    MsgBox "All of the macros have been run."

End Sub

Private Sub FirstPart()
    MsgBox "This is the first macro"

End Sub

Private Sub SecondPart()
    Dim answer As Long
    answer = MsgBox("Do you want to stop the macros?", vbYesNo)

    If answer = vbYes Then
        'Stops All macros!
        End
    End If

    MsgBox "You clicked ""NO"" so the macros are still rolling..."
End Sub

Private Sub ThirdPart()
    MsgBox "Final Macro was run."
End Sub

answered Jun 19, 2019 at 1:33

pgSystemTester's user avatar

pgSystemTesterpgSystemTester

8,7802 gold badges22 silver badges49 bronze badges

Доброго дня!
Прошу помочь в решении вопроса по прерыванию макроса в случае определенного условия.

Есть написанный макрос, состоящий из нескольких макросов. Итоговый макрос составлен примерно так:

Код
Sub top_macro()

call macro_1
call macro_2
call macro_3
call macro_4


end sub

Сам макрос top_macro работает нормально, все макросы командой call вызываются, срабатывают.
Но возникла проблема в прерывании макроса при нахождении ошибки.

Мне необходимо прервать весь макрос top_macro, если в макросе macro_1 возникнет определенное условие. Это условие отлавливаю, вижу существование условия через debug.print, добавляю код EXIT SUB, но он срабатывает 1 раз из 3-4 запусков. То есть, остановки работы главного макроса не происходит и далее начинают выполняться macro_2, macro_3 и т.д.

Подскажите, пожалуйста, возможно, кодом EXIT SUB я прерываю работу только макроса, в котором этот код прописан ( то есть, macro_1) ?
Как сделать так, чтобы прерывался весь макрос top_macro?

Спасибо!

You can interrupt a macro in Excel at any time by pressing Esc or Ctrl + Break.

Place a command button on your worksheet and add the following code lines:

Dim x As Long
x = 5

Do While x > 2
    x = x + 1
Loop

1. Click the command button on the sheet. This macro never stops because the part after ‘Do While’ will always be true (x will always be higher than 2).

2. To halt this infinite loop, press Esc or Ctrl + Break. The following dialog box will appear:

Code Interrupted Dialog Box

3. Click End to end the macro, click Debug to take a look at the macro in the Visual Basic Editor.

4. Add the following code line at the start of your code if you don’t want users of your program to be able to interrupt your macro (not recommended).

Application.EnableCancelKey = xlDisabled

5. Although Excel VBA resets the EnableCancelKey property automatically to xlInterrupt at the end of your macro, it’s good practice (when using the previous code line) to end your macro with the following code line:

Application.EnableCancelKey = xlInterrupt

Note: if Excel freezes and you cannot interrupt your macro anymore, press Ctrl + Alt + Delete and close Excel.

vba end

Often we think about beginnings not endings. It is only when we get somewhere it is when we realize we hadn’t thought through our destination. Same goes for writing VBA macros. Fortunately the VBA End statement is here to save the day and help us put that full-stop in the right place. Today I want to share a cool VBA tip for properly ending your VBA macros i.e. how to abort a macro.

The VBA End statement ends the execution of a certain VBA scope.

VBA End statement

The VBA End Statement is used to mark the end of a specific VBA scope:

'End a Function definition, Sub definition, With statement, Select statement, Type definition, Enum defition, If statement
End [Function | Sub | With | Select | Type | Enum | If ]

You can End a Function, a conditional If statement, mark the End of an VBA Enum or VBA Type. The End statement cannot be used within loop, function or procedure to end its execution prematurely. For that we need to use the VBA Exit statement instead.

So to summarize – End marks the end of a specific VBA scope similarly like { } brackets in C# or tabs in Python.

VBA Exit statement

The VBA Exit Statement is used to exit a particular scope earlier than defined by the VBA End Statement.

'Exit earlier a Do-While/Until loop, For loop, Function/Sub, Select statement 
Exit [ Do | For | Function | Select | Sub ]  

In should be used to end the execution of a loop, function or procedure earlier.

See example below to understand the difference between VBA End and VBA Exit:

Sub SomeProcedure
   '...
   If iWantToExit Then 
     Exit Sub 'if the statement is True this will stop any further execution of this Sub
   End if
   '...
End Sub  'This ends the statement of the Sub procedure

Exiting VBA Functions or Procedures

Sometimes however we want to end the execution of a function or procedure early, simply by leaving the current execution scope.

Exit Sub

Ending Sub procedures is very useful. Instead of using the End statement we need to use the VBA Exit statement.

Sub SomeSub()
    '...
    'Your code here
    '...
    Exit Sub 'Exit the Sub without executing code below
    '...
    'This code will not be executed
    '...
End Sub

Exit Function

Similarly for Functions we need to use the Exit statement instead of End.

Function SomeFunction() as Integer
    '...
    'Your code here
    SomeFunction = 1
    Exit Function 'Exit the Function without executing code below
    '...
    'This code will not be executed
    SomeFunction = 2
End Function

The result of the VBA Function above is 1 not 2.

Exit VBA Loop

You can also use Exit to exit a VBA Loop statement:

For i = 0 to 10
   '...
   If wantToexit = True Then 
      Exit For 'Will exit For loop without executing code below before Next i
   End if
   '...
Next i

The result of the VBA Function above is 1 not 2.

End VBA macro / Reset VBA macro

Now here is the trick I want to sell you today. The Exit statement above will allow you to leave the scope of your current VBA Function or VBA Sub. It will not however end the execution of your entire macro. A simple example below:

Sub Main()
    Call SomeSub 
    'Code will execute
    Debug.Print "Main: Hello after Exit Sub!"
End Sub

Sub SomeSub()
    Exit Sub
    'Code will not execute
    Debug.Print "SomeSub: Hello after Exit Sub!"
End Sub

The result:
The result of running Exit Sub
So you see Exit Sub exiting only the the current scope of the running VBA Sub procedure and not the entire macro!

End – as simple as that

How to exit the execution of the entire macro (the Main Sub)? A simple End will do…

Sub Main()
    Call SomeSub 
    'Code will not execute
    Debug.Print "Main: Hello after Exit Sub!"
End Sub

Sub SomeSub()
    End
    'Code will not execute
    Debug.Print "SomeSub: Hello after Exit Sub!"
End Sub

The result:
Using the VBA End statement to exit macro execution
The End statement ends the execution of the ENTIRE MACRO.

Use End carefully!

As Andy Pope has rightfully corrected me, the End statement needs to be used with care. As there are consequences…

The VBA Reset buttonThe VBA End statement works a lot like the VBA Reset button. This is what happens:

  • Object events will not be invoked e.g. the Unload, QueryUnload, or Terminate events
  • Any running Visual Basic code will be stopped – that means Timers and other running code
  • Object references held by other programs are invalidated – if any application is holding a reference to a VBA object it will be invalidated and inaccessible
  • Closes any open dialogs / forms (e.g. UserForm or MsgBox)

Using End is a lot like pulling a hand brake in a car. It stops the car, but often so abruptly it might cause it to crash.

Понравилась статья? Поделить с друзьями:
  • Vba excel как заблокировать ячейки в excel
  • Vba excel как добавить столбец
  • Vba excel как добавить колонку
  • Vba excel как добавить кнопку на лист excel
  • Vba excel как вызвать форму