Оператор goto vba excel

Home / VBA / VBA GoTo Statement

VBA GoTo statement helps code execution to jump to a specific line within the procedure. In simple words, with the goto statement, VBA jumps to a particular line that is specified by you. For example, if you have specified to jump to the second line go will jump to that line.

How to use VBA GoTo Statement in a Code

  1. First, you need to use the goto statement.
  2. After that, you need to define the place where you want to VBA to jump from goto.
  3. Next, create the tag to create that place in the procedure.
  4. In the end, add the line(s) of code that you want to get executed.
vba-go-to-statement-in-code
Sub vba_goto()
GoTo Last Range("A1").Select Last:
Range("A12").Select
End Sub

GoTo to Repeat a Code

You can also use the go to statement to repeat a code using a set of condition.

Sub goto_repeat()
Dim iMessage As String
Question:
    iMessage = InputBox("what's the day today?")
If iMessage <> "tuesday" Then
    MsgBox ("wrong answer, try again.")
    GoTo Question
Else
    MsgBox ("that's the right answer.")
End If
End Sub

When you run the above code it asks you for the day name and if you enter anything other than “Tuesday” it will repeat the question. If you look at the code, you can see we have to use the goto statement and the if statement.

Now when the user enters anything other than the right answer, the goto statement makes VBA repeat the code. (but whenever you are using these sorts of codes you need to be extra cautious as it can create an endless loop.

VBA GoTo End

You can also exit a sub using the goto statement.

vba-go-to-end

In the above code, we have used the “last” tag just before the end statement and when VBA reaches the GoTo statement, it makes VBA jump to the “Last” at the end of the procedure.

GoTo Statement to go to a Line in Another Sub Routine

Well, go to statement as quite handy to make VBA jump from one place to another, but it’s not possible to make it go to another procedure in the module.

Переход к заданному диапазону или к процедуре VBA в любой открытой книге Excel с помощью метода Application.Goto, неактивная книга активируется.

Application.Goto — это метод, который активирует указанную книгу, если она неактивна, и выделяет заданный диапазон ячеек или отображает заданную процедуру в редакторе VBA.

Если книга Excel в ссылке для перехода не будет указана, выбор диапазона ячеек или процедуры VBA будет осуществлен в активной книге.

Синтаксис

Синтаксис метода Application.Goto:

Application.Goto (Reference, Scroll)

Параметры

Параметры метода Application.Goto:

Параметр Описание
Reference Ссылка на объект Range или на процедуру VBA. Необязательный параметр. Если этот аргумент опущен, будет отображен последний диапазон, выбранный методом Goto или вручную.
Scroll Задает способ прокрутки выбранного диапазона:

  • True — верхний левый угол диапазона прокручивается до верхнего левого угла окна.
  • False — выбранный диапазон отображается в нижней часть окна.

Необязательный параметр. Значение по умолчанию — False.

Примечания

  • Заданный диапазон можно выделить с помощью метода Range.Select, но он не работает с прокруткой листа.
  • При использовании метода Application.Goto для выделения диапазона ячеек, предыдущие выборы сохраняются (до 4 выборов)*.
  • Тесты показали, что методы Application.Goto и Range.Select не работают со свернутыми книгами (Application.WindowState = xlMinimized).

* Просмотреть сохраненные выборы диапазонов ячеек методом Application.Goto можно с помощью свойства Application.PreviousSelections:

Sub PrevSel()

Dim i As Byte

On Error GoTo Instr

    For i = LBound(Application.PreviousSelections) To UBound(Application.PreviousSelections)

        MsgBox Application.PreviousSelections(i).Address

    Next i

Exit Sub

Instr:

    MsgBox «Предыдущих выборов нет»

End Sub

Примеры

Application.Goto для активной книги

Переход к заданному диапазону или к процедуре VBA в активной книге Excel:

‘Отображение процедуры «Test», расположенной в «Module1» активной книги

Application.Goto «Module1.Test»

‘Выделение диапазона

Application.Goto Sheets(«Лист1»).Range(«A40:E50»)

Application.Goto Sheets(«Лист1»).Range(«A40:E50»), True

Application.Goto для любой книги

Переход к заданному диапазону или к процедуре VBA в любой открытой книге Excel:

‘Отображение процедуры «Test», расположенной в «Module1» книги «Книга2.xlsm»

Application.Goto «Книга2.xlsm!Module1.Test»

‘Выделение диапазона

Application.Goto Workbooks(«Книга2.xlsm»).Sheets(«Лист1»).Range(«A40:E50»)

Application.Goto Workbooks(«Книга2.xlsm»).Sheets(«Лист1»).Range(«A40:E50»), True


title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Application.Goto method (Excel)

vbaxl10.chm133144

vbaxl10.chm133144

excel

Excel.Application.Goto

ce60e6d4-18e5-056c-229e-8c0b730109ae

04/04/2019

medium

Application.Goto method (Excel)

Selects any range or Visual Basic procedure in any workbook, and activates that workbook if it’s not already active.

Syntax

expression.Goto (Reference, Scroll)

expression A variable that represents an Application object.

Parameters

Name Required/Optional Data type Description
Reference Optional Variant The destination. Can be a Range object, a string that contains a cell reference in R1C1-style notation, or a string that contains a Visual Basic procedure name. If this argument is omitted, the destination is the last range you used the Goto method to select.
Scroll Optional Variant True to scroll through the window so that the upper-left corner of the range appears in the upper-left corner of the window. False to not scroll through the window. The default is False.

Remarks

This method differs from the Select method in the following ways:

  • If you specify a range on a sheet that’s not on top, Microsoft Excel will switch to that sheet before selecting. (If you use Select with a range on a sheet that’s not on top, the range will be selected but the sheet won’t be activated).

  • This method has a Scroll argument that lets you scroll through the destination window.

  • When you use the Goto method, the previous selection (before the Goto method runs) is added to the array of previous selections (for more information, see the PreviousSelections property). Use this feature to quickly jump between as many as four selections.

  • The Select method has a Replace argument; the Goto method doesn’t.

Example

This example selects cell A154 on Sheet1 and then scrolls through the worksheet to display the range.

Application.Goto Reference:=Worksheets("Sheet1").Range("A154"), _ 
 scroll:=True

[!includeSupport and feedback]

VBA GoTo

Excel VBA GoTo Statement

VBA Goto Statement is used for overcoming the predicted errors while we add and create a huge code of lines in VBA. This function in VBA allows us to go with the complete code as per our prediction or assumptions. With the help Goto we can go to any specified code of line or location in VBA. There is two way of doing it which we will see in upcoming examples.

How to Use Excel VBA Goto Statement?

We will learn how to use Excel VBA Goto Statement with a few examples.

You can download this VBA GoTo Excel Template here – VBA GoTo Excel Template

Example #1

The first way of using VBA Goto is by Application.Goto method. With the help of Application.Goto statement we can to any specific location, workbook or worksheet which is opened currently. This statement will look like as below.

VBA GoTo Syntax

  • [Reference]: This is nothing but a specified cell reference. If the reference is not provided by default it will take you to the last used cell range.
  • [Scroll]: This a logical statement of TRUE or FALSE. If the value is TRUE it will scroll through the window, if the value if FALSE it will not scroll through the window.

For this go to the VBA window and click on Module which is in Insert menu as shown below.

Insert Module

Now it will open a new Module. There write the Subcategory of a macro with the name of Goto as we are performing that code as shown below.

Code:

Sub VBAGoto()

End Sub

VBA GoTo Example 1-1

Now write Application.Goto to enable to application or place where we want to go.

Code:

Sub VBAGoto()

Application.Goto

End Sub

VBA GoTo Example 1-2

After that give Reference to any worksheet or workbook and range of cells. Here we have given the range of Cell B3 and Worksheets of named as “VBA Goto”.

Code:

Sub VBAGoto()

Application.Goto Reference:=Worksheets("VBA_Goto1").Range("B3"),

End Sub

VBA GoTo Example 1-3

Now for actually going to the mentioned cell we need to add Scroll argument which will directly take us to the specified cell. Now we will change the scroll argument from FALSE as shown below.

Code:

Sub VBAGoto()

Application.Goto Reference:=Worksheets("VBA_Goto1").Range("B3"), Scroll:=False

End Sub

VBA GoTo Example 1-4

After running the code using F5 key or manually, we will see cursor will get shifted to cell B3 without changing the orientation of the selected sheet as shown below.

Example 1-5

Now we will change Scroll argument from FALSE to TRUE.

Code:

Sub VBAGoto()

Application.Goto Reference:=Worksheets("VBA_Goto1").Range("B3"), Scroll:=True

End Sub

 Example 1-6

Initially, we are keeping the cursor at cell A5 as shown below. Now run the complete code using F5 key or manually. We will see the cursor which was at cell A5, is now scrolled up and shifted to cell B3 and the whole table has moved to the top level of sheet starting with the same cell which B3 as shown in below screenshot.

Example 1-7

Example #2

There is another way of using VBA Goto argument. Using Goto in VBA by this example, we can skip the argument which is causing an error. For this, insert a new module in VBA and start Subcategory with the name of argument used as shown below. You can use any other name.

Code:

Sub VBAGoto()

End Sub

VBA GoTo Example 2-1

For this, we will consider 3 integers X, Y, and Z by opening Sub category in VBA as shown below.

Code:

Sub VBAGoto()

Dim X As Integer, Y As Integer, Z As Integer

End Sub

VBA GoTo Example 2-2

Now also consider some mathematical division where we will divide 10, 20 and 30 with 0, 2 and 4 as shown below.

Code:

Sub VBAGoto()

Dim X As Integer, Y As Integer, Z As Integer

X = 10 / 0
Y = 20 / 2
Z = 30 / 4

End Sub

VBA GoTo Example 2-3

If we run the code we will get the same error message of Run-time error 11.

Example 2-4

Above error message Run-time error ‘11’ comes only when the written mathematical expression is incorrect. Now to overrule this error, we will use text On Error GoTo with word YResult to skip error message and get the output which works fine as shown below.

Example 2-5

Still, our code is not complete. Using Goto with statement “YResult:” will only skip the error line of code. But it will again show the error as Labe not defined as shown below.

Code:

Sub VBAGoto()

Dim X As Integer, Y As Integer, Z As Integer

On Error GoTo YResult:

X = 10 / 0
Y = 20 / 2
Z = 30 / 4

End Sub

VBA GoTo Example 2-6

Now to complete it, we need to define the Label. Label is the part of statement in VBA Coding, which is used when we want to skip a certain portion of code to any defined applicable line of code. As we already have YResult with Goto argument. Then we will insert the same just before integer Y. Now run the code again.

Code:

Sub VBAGoto()

Dim X As Integer, Y As Integer, Z As Integer

On Error GoTo YResult:

X = 10 / 0

YResult:

Y = 20 / 2

Z = 30 / 4

End Sub

VBA GoTo Example 2-7

As seen and done, we have not got any error message which means that our code is correct and it is skipping that line of code which was causing an error and giving the output where the correct code has been written. Now to print the result of code need to insert message boxes for each Integer with the help argument MsgBox as shown below.

Code:

Sub VBAGoto()

Dim X As Integer, Y As Integer, Z As Integer

On Error GoTo YResult:

X = 10 / 0

YResult:

Y = 20 / 2

Z = 30 / 4

MsgBox X
MsgBox Y
MsgBox Z

End Sub

VBA GoTo Example 2-8

Once done then run the complete code to see the output. We will the output of division of each defined integers as 0, 10 and 8 as shown in below screenshot as well.

Example 2-9

On Error GoTo YResult statement helped us to directly jump to mentioned result point integer as we did for integer Y. And the output for X as 0 shows that there was incorrect statement argument written. We can the Label even before Z but that would give us the result of Z integer only. For X and Y it will again show 0 as output.

Pros of VBA On Error

  • We can calculate any mathematical formula even if it is incorrect.
  • For bigger coding structures where there are chances or having an error, using GoTo may give correct result even among the line of codes.
  • This gives better result as compared to the result obtained from normal excel calculations in spite of having an incorrect argument.

Things To Remember

  • Remember to the file in Macro-Enabled Excel file so that we can use created VBA code many and multiple times.
  • Compile the written code before implementing with any excel requirement.
  • You can assign the written code to any button so that we can quickly click on the button and run the code.
  • Use Label as shown in example-2 appropriately so that we will get the result for the complete correct code.

Recommended Articles

This has been a guide to VBA GoTo Statement. Here we discussed how to use Excel VBA GoTo Statement along with some practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA Loops
  2. VBA Function
  3. VBA VLOOKUP
  4. VBA On Error Goto

VBA GoTo statement one can use when an error occurs while running the code rather than displaying an error to resume the next line of code by ignoring the error message. There are two kinds of GOTO statements: select any worksheet range in the specified workbook and error handler.

To overcome the anticipated errors in VBA, we have a function called “GOTO.” We will see both kinds of GoTo statements in this article.

Table of contents
  • Excel VBA GoTo Statement
    • 2 Ways to use GoTo Statement in VBA Code
      • #1 – Application.GoTo Method
        • Example
      • #2 – Error Handler Method
    • Things to Remember
    • Recommended Articles

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA GoTo Statement (wallstreetmojo.com)

2 Ways to use GoTo Statement in VBA Code

You can download this VBA GoTo Excel Template here – VBA GoTo Excel Template

#1 – Application.GoTo Method

We can use the statement Application if you want to go to the specific workbook or worksheet in all the opened Workbooks.GoTo method.

Let us look at the syntax of the Application.GoTo method.

VBA Go to Formula

  • [Reference]: This is nothing but a specific cell referenceCell reference in excel is referring the other cells to a cell to use its values or properties. For instance, if we have data in cell A2 and want to use that in cell A1, use =A2 in cell A1, and this will copy the A2 value in A1.read more. If the reference is not there by default, it will take you to the last used cell range.
  • [Scroll]: This is a logical statement of TRUE or FALSE. If the value is TRUE, it will scroll through the window. If the value is FALSE, it will not scroll through the window.
Example

We can use the Goto method if you want to go to a specific cell in the worksheet. For example, we have 3 sheets: Jan, Feb, and Mar.

VBA Go to Example 1

If we want to go to cell C5 in the Jan sheet, we will use the below set of codes.

Step 1: Start the excel macroA macro in excel is a series of instructions in the form of code that helps automate manual tasks, thereby saving time. Excel executes those instructions in a step-by-step manner on the given data. For example, it can be used to automate repetitive tasks such as summation, cell formatting, information copying, etc. thereby rapidly replacing repetitious operations with a few clicks.
read more
name.

Code:

Sub GoTo_Example1()

End Sub

VBA Go to Example 1-1

Step 2: Start the method “Application.GoTo

Code:

Sub GoTo_Example1()

Application.Goto

End Sub

VBA Go to Example 1-2

Step 3: We need to specify the worksheet name in the reference argument. Then, in that worksheet, we need to mention the specific cell.

Code:

Sub GoTo_Example1()

Application.Goto Reference:=Worksheets("Jan").Range("C5")

End Sub

VBA Go to Example 1-3

Step 4: Mention the scroll as TRUE.

Code:

Sub GoTo_Example1()

Application.Goto Reference:=Worksheets("Jan").Range("C5"),Scroll:=True

End Sub

VBA Go to Example 1-4

Step 5: Now, run this code using the F5 key, or you can also run it manually. It will take you to the specified sheet and specified cell.

Example 1-5

Example 1-6

Now, we will change the scroll argument to FALSE and see the change it will encounter.

Sub GoTo_Example1()

Application.Goto Reference:=Worksheets("Jan").Range("C5"), Scroll:=False

End Sub

Example 1-7

If you want to go to a specific workbook, you need to mention the workbook name before the workbook name.

Sub GoTo_Example1()

Application.Goto Reference:=Workbooks("Book1.xlsx").Worksheets("Jan").Range("C5"), Scroll:=False

End Sub

#2 – Error Handler Method

When a particular line of code encounters an error, VBA stops executing the rest of the code and shows the error message.

For example, look at the below line of code.

Sub GoTo_Example2()

  Sheets("April").Delete

  Sheets.Add

End Sub

The above code says to delete the sheet in April and add a new sheet. In the active workbook, if there is any sheet named April, it will delete or show the below error message dialog box.

Example 1-8

When we ran this code, the workbook did not have a sheet called April, so the VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more could not find the sheet name and threw the error. Sometimes, we need to ignore this error because often, if there is no sheet name called April, then we need to go on with the other lines of code.

We can use the GoTo method as an error handler to eliminate this error.

We will modify the code as the “On Error” goes to the next line.

Sub GoTo_Example2()

On Error GoTo NextLine
Sheets("April").Delete

NextLine:
Sheets.Add

End Sub

If we run this, it will add the new sheet even though there is no sheet named April.

The statement “On Error GoTo NextLine” understands that if any error occurs, it will jump to the next line, and in the next line, the VBA code is to add a new sheet.

Things to Remember

  • We can also use the On Error Resume Next VBAVBA On Error Resume Statement is an error-handling aspect used for ignoring the code line because of which the error occurred and continuing with the next line right after the code line with the error.read more statement if you want to jump to the next line when the error occurs.
  • To jump to the next, we must be sure that that particular line of code expected must be an error.
  • If the important line of the code skips with this error handler, we may not finish your task perfectly.

Recommended Articles

This article has been a guide to VBA GoTo. Here we learn how to use the VBA GoTo statement using the Application.GoTo and Error Handler Method along with examples and downloadable Excel template. Below are some useful Excel articles related to VBA: –

  • MsgBox in Excel VBA
  • Excel VBA On Error Goto 0
  • Excel VBA GoTo Statement
  • VBA Selection

Понравилась статья? Поделить с друзьями:
  • Оператор excel пустая ячейка
  • Оператор excel заменяет функцию
  • Оператор dim vba excel
  • Оператор and в строке фильтра в excel
  • Оператор and в word