Vba для excel метки

Содержание

  1. Оператор GoTo
  2. Синтаксис
  3. Часть
  4. Remarks
  5. Ветвление и пробная конструкция
  6. Пример
  7. Application.Goto method (Excel)
  8. Syntax
  9. Parameters
  10. Remarks
  11. Example
  12. Support and feedback
  13. Метод Application.Goto (Excel)
  14. Синтаксис
  15. Параметры
  16. Замечания
  17. Пример
  18. Поддержка и обратная связь
  19. VBA Excel. Элемент управления Label (метка, надпись)
  20. Элемент управления Label
  21. Свойства элемента Метка
  22. Примеры кода VBA с Label
  23. VBA GoTo a Line Label
  24. GoTo Examples
  25. GoTo Multiple Line Labels
  26. GoTo Error Handler End of Procedure
  27. GoTo Repeat Code
  28. VBA GoTo a Line Label in Access VBA
  29. VBA Coding Made Easy
  30. VBA Code Examples Add-in

Оператор GoTo

Ветвления безоговорочно к указанной строке процедуры.

Синтаксис

Часть

line
Обязательный. Любая метка строки.

Оператор GoTo может ветвиться только к строкам в процедуре, в которой она отображается. Строка должна иметь метку строки, на которую GoTo можно ссылаться. Дополнительные сведения см. в разделе «Практическое руководство. Операторы меток».

GoTo операторы могут затруднить чтение и обслуживание кода. По возможности используйте вместо нее структуру управления. Дополнительные сведения см. в разделе Поток управления.

Оператор нельзя использовать GoTo для ветвления за пределами For . Next , For Each . Next , SyncLock . Try . End SyncLock Catch . Finally , With . End With , или Using . End Using конструкция на метку внутри.

Ветвление и пробная конструкция

Try Внутри . Catch . Finally Конструкции, следующие правила применяются к ветвлениям с помощью инструкции GoTo .

Блокировка или регион Ветвление извне Ветвление изнутри
Блок Try Только из Catch блока той же конструкции 1 Только за пределами всей конструкции
Блок Catch Никогда не допускается Только за пределами всей конструкции, или к Try блоку того же строительства 1
Блок Finally Никогда не допускается Никогда не допускается

1 Если один Try . Catch . Finally Построение вложено в другой блок, Catch блок может ветвить в Try блок на собственном уровне вложения, но не в любой другой Try блок. Вложенный Try . Catch . Finally конструкция должна содержаться полностью в блоке Try Catch конструкции, в которой она вложена.

На следующем рисунке показана одна Try конструкция, вложенная в другую. Различные ветви между блоками двух конструкций указываются как допустимые или недопустимые.

Пример

В следующем примере оператор используется GoTo для ветвления к подписям в процедуре.

Источник

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.

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.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Метод Application.Goto (Excel)

Выбирает любой диапазон или процедуру Visual Basic в любой книге и активирует ее, если она еще не активна.

Синтаксис

expression. Goto (справочник, прокрутка)

выражение: переменная, представляющая объект Application.

Параметры

Имя Обязательный или необязательный Тип данных Описание
Reference Необязательный Variant Назначение. Может быть объектом Range , строкой, содержащей ссылку на ячейку в нотации в стиле R1C1, или строкой, содержащей имя процедуры Visual Basic. Если этот аргумент опущен, назначение будет последним диапазоном, который использовался для выбора метода Goto .
Scroll Необязательный Variant Значение true для прокрутки окна, чтобы верхний левый угол диапазона отображалось в левом верхнем углу окна. Значение false , чтобы не прокручивать окно. Значение по умолчанию — false.

Замечания

Этот метод отличается от метода Select следующими способами:

Если вы укажете диапазон на листе, который не находится наверху, Microsoft Excel переключится на этот лист, прежде чем выбрать его. (Если вы используете Команду с диапазоном на листе, который не находится сверху, диапазон будет выбран, но лист не будет активирован).

Этот метод содержит аргумент Scroll , который позволяет прокручивать целевое окно.

При использовании метода Goto предыдущее выделение (перед выполнением метода Goto ) добавляется в массив предыдущих выделенных фрагментов (дополнительные сведения см. в свойстве PreviousSelections ). Используйте эту функцию для быстрого перехода между четырьмя выбранными вариантами.

Метод Select имеет аргумент Replace ; Метод Goto не поддерживает.

Пример

В этом примере выбирается ячейка A154 на листе Лист1, а затем прокручивается лист для отображения диапазона.

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

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

Источник

VBA Excel. Элемент управления Label (метка, надпись)

Элемент управления пользовательской формы Label, применяемый в VBA Excel для отображения надписей, меток, информационного текста. Свойства Label, примеры кода.

Элемент управления Label

Элемент управления Label, как и другие элементы управления, реагирует на нажатия мышью, то есть его можно использовать для запуска подпрограмм, изменения собственных свойств, свойств пользовательской формы и других элементов управления.

Свойства элемента Метка

Свойство Описание
AutoSize Автоподбор размера надписи. True – размер автоматически подстраивается под длину набираемой строки. False – размер элемента управления определяется свойствами Width и Height.
Caption Текст надписи (заголовок).
ControlTipText Текст всплывающей подсказки при наведении курсора на метку.
Enabled Возможность взаимодействия пользователя с элементом управления Label. True – взаимодействие включено, False – отключено (цвет текста становится серым).
Font Шрифт, начертание и размер текста надписи.
Height Высота элемента управления.
Left Расстояние от левого края внутренней границы пользовательской формы до левого края элемента управления.
Picture Добавление изображения вместо текста метки или дополнительно к нему.
PicturePosition Выравнивание изображения и текста в поле надписи.
TabIndex Определяет позицию элемента управления в очереди на получение фокуса при табуляции, вызываемой нажатием клавиш «Tab», «Enter». Отсчет начинается с 0.
TextAlign* Выравнивание текста надписи: 1 (fmTextAlignLeft) – по левому краю, 2 (fmTextAlignCenter) – по центру, 3 (fmTextAlignRight) – по правому краю.
Top Расстояние от верхнего края внутренней границы пользовательской формы до верхнего края элемента управления.
Visible Видимость элемента управления Label. True – элемент отображается на пользовательской форме, False – скрыт.
Width Ширина элемента управления.
WordWrap Перенос текста надписи на новую строку при достижении ее границы. True – перенос включен, False – перенос выключен.

* При загруженной в надпись картинке свойство TextAlign не работает, следует использовать свойство PicturePosition.

Свойство по умолчанию для элемента Label – Caption, основное событие – Click.

В таблице перечислены только основные, часто используемые свойства надписи. Все доступные свойства отображены в окне Properties элемента управления Label.

Примеры кода VBA с Label

Пример 1
Загрузка элемента управления Label на пользовательскую форму с параметрами, заданными в коде VBA Excel:

Источник

VBA GoTo a Line Label

In this Article

The GoTo Statement in VBA allows you to jump to a line of code.

First create a line label anywhere in your code:

Then add to “GoTo” statement to jump to the line label

GoTo Examples

This example tests the year. If the year is 2019 or later it will GoTo the Skip line label. This allows you to skip over code if certain conditions are met.

GoTo Multiple Line Labels

You can also use GoTo statements to jump to relevant lines of code. Let’s adjust our previous example to go to different code locations based on which year it is:

Notice the “GoTo EndProc” before each line label. We added this line of code so that those code sections are skipped unless they are accessed by the relevant “GoTo”.

GoTo Error Handler End of Procedure

Now let’s use Error Handling to go to the end of the procedure if there is an error.

GoTo Repeat Code

Our last example will use the GoTo Statement to repeat some code.

Below we’re using a Yes / No Messagebox (Click to learn more) to confirm that the user acknowledges the warning. If they click ‘No’, the message box will be displayed again until they click ‘Yes’ (see GIF below).

VBA GoTo a Line Label in Access VBA

All of the above examples work exactly the same in Access VBA as in Excel VBA.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

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]

Return to VBA Code Examples

In this Article

  • GoTo Examples
  • GoTo Multiple Line Labels
    • GoTo Error Handler End of Procedure
    • GoTo Repeat Code
  • VBA GoTo a Line Label in Access VBA

The GoTo Statement in VBA allows you to jump to a line of code.

First create a line label anywhere in your code:

Skip:

Then add to “GoTo” statement to jump to the line label

GoTo Skip

GoTo Examples

This example tests the year. If the year is 2019 or later it will GoTo the Skip line label. This allows you to skip over code if certain conditions are met.

Sub GoTo_Example()

    Dim year As Integer
    year = 2019

    If year >= 2019 Then GoTo Skip
    
    'Process Data for Years < 2019
     MsgBox "Year is Prior to 2019"

Skip:
End Sub

GoTo Multiple Line Labels

You can also use GoTo statements to jump to relevant lines of code.  Let’s adjust our previous example to go to different code locations based on which year it is:

Sub GoTo_Statement()

    Dim year As Integer
    year = 2019

    If year = 2019 Then
        GoTo year2019
    ElseIf year = 2010 Then
        GoTo year2020
    Else
        GoTo year2021
    End If
    
year2019:
    'Process 2019
    MsgBox "Year is 2019"


GoTo EndProc
year2020:
    'Process 2020
    MsgBox "Year is 2020"


GoTo EndProc
year2021:
    'Process 2021+
    MsgBox "Year is 2021+"


EndProc:
End Sub

Notice the “GoTo EndProc” before each line label. We added this line of code so that those code sections are skipped unless they are accessed by the relevant “GoTo”.

GoTo Error Handler End of Procedure

Now let’s use Error Handling to go to the end of the procedure if there is an error.

Sub GoTo_OnError ()
Dim i As Integer

On Error GoTo EndProc


    i = 5 / 0
    MsgBox i


EndProc:
End Sub

GoTo Repeat Code

Our last example will use the GoTo Statement to repeat some code.

Below we’re using a Yes / No Messagebox (Click to learn more) to confirm that the user acknowledges the warning. If they click ‘No’, the message box will be displayed again until they click ‘Yes’ (see GIF below).

Sub GoTo_YesNoMsgBox()

RepeatMsg:
    Dim answer As Integer
    
    answer = MsgBox("WARNING: This file was opened as a Read-Only file, meaning any changes you make will not be saved unless/until you have Write-Access rights. " & _
    Chr(13) & Chr(13) & "Select  File, SaveAs  to save a copy before working in this file." & vbNewLine & vbNewLine & "Do you understand?", vbExclamation + vbYesNo, "WARNING!")
    
    If answer = vbNo Then GoTo RepeatMsg 'Repeat until user clicks "Yes"

End Sub

go to line label

VBA GoTo a Line Label in Access VBA

All of the above examples work exactly the same in Access VBA as in Excel VBA.

Sub TestGoTo()
   On Error GoTo ending
   DoCmd.OpenForm "FrmClients"
   Exit Sub
   ending:
   MsgBox "Cannot open form"
End Sub

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

Инструкции безусловного перехода

С помощью инструкций безусловного перехода можно приступать к выполнению части заданной программы без проверки каких-либо условий. К таким инструкциям относятся GoTo и пара GoSub-Return. Однако перед их рассмотрением необходимо ознакомиться еще с одним элементом языка VBA, без которого данные инструкции использоваться не могут, – с метками.

Метки

Метка – это идентификатор VBA или целое число, которое располагается в начале строки и заканчивается двоеточием. Метки используются для указания строк, на которые можно переходить с помощью инструкций GoTo и GoSub. Примеры меток приведены ниже:

100:

DoSomeAction:

Перерасчет:

После перехода на метку выполняются все инструкции, расположенные после нее до конца процедуры, функции, следующих инструкций GoTo, GoSub или до инструкции Return (см. далее).

Инструкция GoTo

Инструкция GoTo используется для простого перехода к выполнению программы после нужной метки. Формат инструкции следующий:

GoTo Имя_метки

Инструкции, расположенные после GoTo, выполняются только в том случае, если в программе существуют соответствующие инструкции GoTo или GoSub. Рассмотрим пример использования GoTo:

a = 15 + b

If a < 0 Then GoTo 10

‘ Выполнение действий для значения переменной a больше нуля

10:

‘ Выполнение действий для значения переменной a меньше нуля

Следует отметить, что частое использование инструкции GoTo в программе не рекомендуется, так как может сделать алгоритм слишком запутанным. GoTo нередко допустимо заменить инструкциями выбора либо вызовом процедуры или функции.

Пара инструкций GoSub-Return

Во времена старого доброго языка Basic инструкции GoSub и Return были незаменимы для программиста. Это было связано с тем, что Basic не был даже процедурным языком программирования: в нем не было процедур и функций, все инструкции записывались в виде единой программы. Чтобы не реализовывать несколько раз одинаковые действия, в этой большой программе выделялись отрезки кода, выполняющие типичные действия, – подпрограммы. Подпрограмма начиналась некоторой меткой и оканчивалась инструкцией Return.

При достижении инструкции Go Sub осуществлялся переход на указанную метку (аналогично инструкции GoTo) – начинала выполняться подпрограмма. При достижении инструкции Return происходил возврат из подпрограммы – выполнение программы продолжалось после последней инструкции Go Sub.

Пара инструкций GoSub-Return в языке VBA работает точно таким же образом, но переходы осуществляются только в пределах процедуры или функции. Формат инструкций GoSub-Return такой:

GoSub Имя_метки

[Инструкции]

Имя_метки:

[Инструкции подпрограммы]

Return

Ниже приведен пример использования инструкций GoSub-Return (в подпрограмме вычисляется квадрат длины гипотенузы прямоугольного треугольника):

a = 5

b = 4

GoSub Calculate

‘ Другие действия

Calculate:

‘ Подпрограмма

c2 = a ^ 2 + b ^ 2

Return

Следует отметить, что при процедурном, а тем более объектно-ориентированном программировании необходимость использования подпрограмм полностью отпала. Роль подпрограмм выполняют функции и процедуры.

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

Понравилась статья? Поделить с друзьями:
  • Vba для excel как установить
  • Vba для excel все команды
  • Vba для excel worksheets
  • Vba для excel optionbutton
  • Vba для excel cells