Vba excel goto next for

 

Nik021

Пользователь

Сообщений: 63
Регистрация: 24.02.2017

#1

01.08.2017 18:46:47

Добрый день.

Есть цикл for, в нем много условий и действие.
Я хочу, чтобы при определенном условии дальнейшие условия не проверялись вообще и переходить к следующему шагу.
Делать многоуровневые конструкции if else не хочется. При проверке каждого условия хочется быть уверенным, что предыдущие условия выдали положительный ответ.
Заранее спасибо.

Код
For i = 1 To 5
        
        q = False
        
        If 1 = 1 Then
            q = True
        Else
            If 1 > 2 Then
                q = True
            Else
                '   перейти к следующему шагу
            End If
        End If
        
        If 3 = 3 Then
            q = True
        Else
            '   перейти к следующему шагу
        End If
        
        
        If 5 = 6 Then
            q = True
        Else
            '   перейти к следующему шагу
        End If
        
        
        If q Then Debug.Print "выполняем действие"
        
    Next
 

The_Prist

Пользователь

Сообщений: 14182
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

Go to?
Еще может имеет смысл присмотреться к Select Case. Но не зная конечной цели сложно точно сказать, подойдет или нет.
ElseIf тоже никто не отменял.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

как может быть 1 > 2 и 5 = 6?

 

Nik021

Пользователь

Сообщений: 63
Регистрация: 24.02.2017

The_Prist,
Go to почему-то все настоятельно рекомендуют не использовать в циклах
Select Case не поможет в моей ситуации

В каждом условии буду вдобавок проверять результат предыдущего условия, пока так…  

 

Equio

Пользователь

Сообщений: 274
Регистрация: 05.05.2016

Continue For

https://msdn.microsoft.com/en-us/library/z6zekeaa(v=vs.100).aspx

Хотя это для VB. Не знаю, будет ли в VBA работать.

Update: Попробовал, не работает в VBA.

Изменено: Equio01.08.2017 19:36:30

 

Hugo

Пользователь

Сообщений: 23251
Регистрация: 22.12.2012

#6

01.08.2017 19:33:21

Цитата
Nik021 написал:
Select Case не поможет в моей ситуации

— как часто слышали это в разных вариантах :)

 

The_Prist

Пользователь

Сообщений: 14182
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#7

01.08.2017 19:38:16

Цитата
Nik021 написал:
Go to почему-то все настоятельно рекомендуют не использовать

значит не используйте, раз Вам так рекомендуют :) Я иногда использую. К слову, если бы это было совсем уж «неграмотно» — его бы не было и в более серьезных языках. Но он там есть. Главное использовать правильно, чтобы эти GoTo не не ломали читаемость кода и главное — были оправданы. Потому как некоторые пихают их там, где без них можно обойтись более чем.
Выбора за Вами.
По поводу Select Case — уже говорил. И Hugo прав — иногда за этим «не поможет» часто стоит просто незнание всех возможностей этой конструкции. Не более.
Да и в любом случае — не видя реальной задачи подсказать больше нечего.

Изменено: The_Prist01.08.2017 19:39:18

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Nik021

Пользователь

Сообщений: 63
Регистрация: 24.02.2017

The_Prist, я искал легкий способ прекратить дальнейшее выполнение кода и перехода к следующему шагу цикла, как, например, exit for (exit полностью завершает цикл, но вы поняли). Рас так просто нельзя, то буду использовать другие доступные варианты. Спасибо.

 

Влад

Пользователь

Сообщений: 1189
Регистрация: 24.12.2012

В таких случаях внутри цикла For…Next делается замкнутый Do…Loop с командой выхода в конце. Любое условие, при котором нужно перейти к следующему шагу Next, выполняет Exit Do.

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

#10

01.08.2017 20:49:51

Цитата
Nik021 написал:
Select Case не поможет в моей ситуации

А мне кажется, что Select Case именно то, что Вам нужно.

 

Nik021

Пользователь

Сообщений: 63
Регистрация: 24.02.2017

Юрий М, Select Case, на сколько я помню, проверяет только числа, а строковые значение сравнивать не умеет или я что-то путаю уже.

Влад, а вот это уже интересная идея !)

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

#12

01.08.2017 21:57:11

Цитата
Nik021 написал:
или я что-то путаю уже.

Или )

 

The_Prist

Пользователь

Сообщений: 14182
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#13

02.08.2017 08:59:56

Цитата
Nik021 написал:
на сколько я помню, проверяет только числа

что-то Вы не то помните. Эта конструкция принимает не просто и числа и текст, но и очень такие выражения в качестве условий, для которых в If … then надо будет городить доп.условия.
Идея с Do .. Loop не очень хорошая. Делать цикл только ради того, чтобы перескочить к концу другого цикла — это уже перебор. Уж в таких случаях куда оправданнее будет тот же GoTo, чем Exit Do в тех же места, не считаете?

Изменено: The_Prist02.08.2017 09:03:02

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Влад

Пользователь

Сообщений: 1189
Регистрация: 24.12.2012

 

The_Prist

Пользователь

Сообщений: 14182
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#15

02.08.2017 13:07:26

Цитата
Влад написал:
Не перевариваю GoTo

Это выбор каждого :) И если мне приведут вменяемое обоснование, чем он так плох — может тоже не буду использовать. Пока что не нашел причин отказываться от него совсем, особенно в ситуациях, где с ним процедура намного лаконичнее, читабельнее и быстрее, чем без него.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Ігор Гончаренко

Пользователь

Сообщений: 13746
Регистрация: 01.01.1970

#16

02.08.2017 14:40:01

и тем более GOTO логически и визуальнео очень органично встраивается в представленнй макрос
достаточно заменить комментарии ‘   перейти к следующему шагу на GOTO Метка, а саму метку поставить перед Next

Скрытый текст

Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете!

 

kuklp

Пользователь

Сообщений: 14868
Регистрация: 21.12.2012

E-mail и реквизиты в профиле.

#17

02.08.2017 14:51:01

Цитата
Ігор Гончаренко написал:
логически и визуальнео очень органично встраивается

тоже сделает ElseIf конструкция без всяких гот и меток ;)

Я сам — дурнее всякого примера! …

Цикл For… Next в VBA Excel, его синтаксис и описание отдельных компонентов. Примеры использования цикла For… Next.

Цикл For… Next в VBA Excel предназначен для выполнения группы операторов необходимое количество раз, заданное управляющей переменной цикла — счетчиком. При выполнении цикла значение счетчика после каждой итерации увеличивается или уменьшается на число, указанное выражением оператора Step, или, по умолчанию, на единицу. Когда необходимо применить цикл к элементам, количество которых и индексация в группе (диапазон, массив, коллекция) неизвестны, следует использовать цикл For Each… Next.


For counter = start To end [ Step step ]

    [ statements ]

    [ Exit For ]

    [ statements ]

Next [ counter ]


For счетчик = начало To конец [ Step шаг ]

    [ операторы ]

    [ Exit For ]

    [ операторы ]

Next [ счетчик ]


В квадратных скобках указаны необязательные атрибуты цикла For… Next.

Компоненты цикла For… Next

Компонент Описание
counter Обязательный атрибут. Числовая переменная, выполняющая роль счетчика, которую еще называют управляющей переменной цикла.
start Обязательный атрибут. Числовое выражение, задающее начальное значение счетчика.
end Обязательный атрибут. Числовое выражение, задающее конечное значение счетчика.
Step* Необязательный атрибут. Оператор, указывающий, что будет задан шаг цикла.
step Необязательный атрибут. Числовое выражение, задающее шаг цикла. Может быть как положительным, так и отрицательным.
statements Необязательный** атрибут. Операторы вашего кода.
Exit For Необязательный атрибут. Оператор выхода из цикла до его окончания.
Next [ counter ] Здесь counter — необязательный атрибут. Это то же самое имя управляющей переменной цикла, которое можно здесь не указывать.

*Если атрибут Step отсутствует, цикл For… Next выполняется с шагом по умолчанию, равному 1.

**Если не использовать в цикле свой код, смысл применения цикла теряется.

Примеры циклов For… Next

Вы можете скопировать примеры циклов в свой модуль VBA, последовательно запускать их на выполнение и смотреть результаты.

Простейший цикл

Заполняем десять первых ячеек первого столбца активного листа Excel цифрами от 1 до 10:

Sub test1()

Dim i As Long

  For i = 1 To 10

    Cells(i, 1) = i

  Next

End Sub

Простейший цикл с шагом

В предыдущий цикл добавлен оператор Step со значением 3, а результаты записываем во второй столбец:

Sub test2()

Dim i As Long

  For i = 1 To 10 Step 3

    Cells(i, 2) = i

  Next

End Sub

Цикл с отрицательными аргументами

Этот цикл заполняет десять первых ячеек третьего столбца в обратной последовательности:

Sub test3()

Dim i As Long

  For i = 0 To 9 Step 1

    Cells(i + 10, 3) = i + 10

  Next

End Sub

Увеличиваем размер шага до -3 и записываем результаты в четвертый столбец активного листа Excel:

Sub test4()

Dim i As Long

  For i = 0 To 9 Step 3

    Cells(i + 10, 4) = i + 10

  Next

End Sub

Вложенный цикл

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

Sub test5()

Dim i1 As Long, i2 As Long

  For i1 = 1 To 10

‘Пятой ячейке в строке i1 присваиваем 0

    Cells(i1, 5) = 0

      For i2 = 1 To 4

        Cells(i1, 5) = Cells(i1, 5) + Cells(i1, i2)

      Next

  Next

End Sub

Выход из цикла

В шестой столбец активного листа запишем названия десяти животных, конечно же, с помощью цикла For… Next:

Sub test6()

Dim i As Long

  For i = 1 To 10

    Cells(i, 6) = Choose(i, «Медведь», «Слон», «Жираф», «Антилопа», _

    «Крокодил», «Зебра», «Тигр», «Ящерица», «Лев», «Бегемот»)

  Next

End Sub

Следующий цикл будет искать в шестом столбце крокодила, который съел галоши. В ячейку седьмого столбца цикл, пока не встретит крокодила, будет записывать строку «Здесь был цикл», а когда обнаружит крокодила, запишет «Он съел галоши» и прекратит работу, выполнив команду Exit For. Это будет видно по ячейкам рядом с названиями животных ниже крокодила, в которых не будет текста «Здесь был цикл».

Sub test7()

Dim i As Long

  For i = 1 To 10

    If Cells(i, 6) = «Крокодил» Then

      Cells(i, 7) = «Он съел галоши»

      Exit For

        Else

      Cells(i, 7) = «Здесь был цикл»

    End If

  Next

End Sub


Результат работы циклов For… Next из примеров:

Результат работы циклов For... Next из примеров

Результат работы циклов For… Next

Такие данные на активном листе Excel вы получите, если последовательно запустите на выполнение в редакторе VBA все семь подпрограмм из примеров, демонстрирующих работу циклов For… Next.

Цикл с дробными аргументами

Атрибуты start, end и step могут быть представлены числом, переменной или числовым выражением:

For i = 1 To 20 Step 2

For i = a To b Step c

For i = a 3 To 2b + 1 Step c/2  

В результате вычисления значения переменной вне цикла или выражения внутри его может получиться дробный результат. VBA Excel округлит его до целого числа, используя бухгалтерское округление:

‘Значения атрибутов до округления

For i = 1.5 To 10.5 Step 2.51

‘Округленные значения атрибутов

For i = 2 To 10 Step 3  

Старайтесь не допускать попадания в тело цикла For… Next неокругленных значений аргументов, чтобы не получить непредсказуемые результаты его выполнения. Если без дробных чисел не обойтись, а необходимо использовать обычное округление, применяйте в коде VBA функцию рабочего листа WorksheetFunction.Round для округления числа перед использованием его в цикле For… Next.


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.

Loops in VBA

Loops are an essential part of any programming language because they help with the repeated running of any code snippet. Just like any other language, VBA offers the following loops to enable efficient programming:

  1. Do until
  2. Do while
  3. For
  4. Foreach

In this article we will dive dep into the “for” loop which iterates only for “x” number of times where “x” is a known value before the loop’s runtime.

“X” can also be a predictable number at runtime, for example when you determine the Lbound and Ubound values of arrays.

The For Loop in VBA

In VBA, “for loop” is easy to use. It follows a simple and understandable syntax.

Syntax:

For <counter> = <start> to <end> [ <step value> ]

[ <code block to execute> ]

Next [ <counter> ]

where

<counter> is the iterator variable which keeps incrementing by the <step value> after every iteration. 

<step value> is optional. If this value is not provided, the default incremental value is “1.”

<Code block to execute> is also optional. It is the snippet of code to be executed during every iteration.

The “Next” statement marks the end of the “for” loop. It indicates to move to the next iteration of this loop with the incremented counter value.

Simple Examples of a For Loop

Print a Mathematical Table for a Number

Sub forloop_demo()
    ' declare all the required variables
    Dim counter, input_number As Integer
    
    ' Receive input from user
    input_number = InputBox(" Which tables do you want to print ? ")
    
    ' Print the mathematical table of the input number upto 12 count
    For counter = 1 To 12
        Debug.Print (counter &amp;amp;amp; " X " &amp;amp;amp; input_number &amp;amp;amp; " = " &amp;amp;amp; counter * input_number)
    Next
            
End Sub

This program receives a number as an input from the user. Then, using a “for” loop, it is multiplied with each number from 1 to 12 to print a “times table” table of that input number.

A sample output of this program if “3” is input by the user is seen in the image below.

A sample output of this program if “3” is input by the user.

Program to Print Contents of an Array

This program defines an array with its size. All elements of the array are assigned values one by one. Next they are printed as we iterate through a loop. It is noteworthy to say that the iterator variable (i) of the “for” loop is also used as the array index inside the loop (this is not mandatory but makes it easy to read/understand/maintain).

Sub array_cars()

'declaring variable while defining its size
Dim arr_my_cars1(5) As Variant

'initialize array elements for one array
 arr_my_cars1(0) = "Benz"
 arr_my_cars1(1) = "Maruthi"
 arr_my_cars1(2) = "Hyundai"
 arr_my_cars1(3) = "Ford"
 arr_my_cars1(4) = "Nissan"

'print all elements of the array
For i = LBound(arr_my_cars1) To UBound(arr_my_cars1)
    Debug.Print arr_my_cars1(i)
Next

End Sub

Output of the Program:

Benz

Maruthi

Hyundai

Ford

Nissan

Program to Write and Read Array Contents

This program slightly varies from the one above. Here you will create an array and iterate through it using its indices. 

Values are given to each array item using a “for” loop initially. (This was not the case in the previous program.)

Then, all the data stored in each element of the same array are read/printed back using another “for” loop.

Two loops are used here one below the other:

  1. One to write data to array
  2. Another one to read data from the same array.
Sub array_check_demo1()

' Declaration of array variable
Dim arr1(11)

' Assign values to array elements
For i = LBound(arr1) To UBound(arr1)
    'Allocate data for each array item through a loop
    arr1(i) = Cells(i + 2, 1).Value
Next

' Print values of the array
For i = LBound(arr1) To UBound(arr1)
    'Read data of each array item through a loop
    Debug.Print arr1(i)
Next
End Sub

Input is taken from the table below:

Principal amount No of yrs Age of customer
10000 5 67
340600 6 45
457800 8 34
23400 3 54
12000 4 23
23545 4 56
345243 2 55
34543 3 24
23223 2 19
3656 1 65

Output of the Program

Output of the "for" loop program

Program That Uses the [step] Value

Check out this program and try to find out why the numbers are not continuous in the output:

Sub step_demo()
' declare a counter
Dim p As Integer

'loop through 10 numbers and print them
For p = 1 To 10 step 3
	Debug.Print p
Next 
End Sub

Output of the Program

1

4

7

10

Yes, you might have found that the iterator variable increments by “3” instead of “1” in every iteration. Hence, the numbers printed are skip counted by “3.”

Try the same with different values in the place of [step] to understand it better if you are still confused.

The Nested “For” Loop

A loop within a loop is called a nested loop. 

Structure

Structure of a nested loop within a loop.

Let me explain this structure with colors:

  1. The for loop structure in yellow color is the outermost loop. 
  2. The for loop structure/block in green color is the inner loop for the outermost (yellow color) loop. But it also acts as the outer loop for the “for loop” structure in turquoise color.
  3. The for loop structure in turquoise color is the innermost loop. 

In this way , we can have any number of nested loops. 

But there are ample chances for you to get confused when you see your own code after several days. You will wonder inside which loop is a specific line and what role it plays in the whole code.

To avoid this, follow the tips below while you code your logic:

  1. Maintain the alignment in your code with proper tab spaces as shown in the structure above. This can help you find the block of code/loop in which your statement is. 

If possible, use the iterator variable next to the “next” keyword. It can help you indicate which “next” statement  marks the closure of which loop. This is also marked in the colored structure for reference.

A Few Examples of Nested For Loops

Program to Format Cells with a Specific Word

This program iterates through all the cells (every column of every row in this case). If the cell content has a word “India,” then the specified formatting is applied to it.

Sub format_cell_with()
For i = 1 To 15
    For j = 1 To 5
    cellcontent = Cells(i, j).Value
    If InStr(cellcontent, "India") &amp;amp;gt; 0 Then
        With Cells(i, j).Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorAccent2
        .TintAndShade = 0.399975585192419
        .PatternTintAndShade = 0
        End With
    End If
    Next
Next

Input sheet:

ICC Men’s Cricket World Cup Winners – 50 Overs
Year World Cup Winner Runners Up Host Finals Venue
1975 West Indies Australia England Lord’s Cricket Ground, London
1979 West Indies England England Lord’s Cricket Ground, London
1983 India West Indies England Lord’s Cricket Ground, London
1987 Australia England India & Pakistan Eden Gardens, Kolkata
1992 Pakistan England Australia & New Zealand Melbourne Cricket Ground, Melbourne
1996 Sri Lanka Australia India, Pakistan & Sri Lanka Gaddafi Stadium, Lahore
1999 Australia Pakistan England Lord’s Cricket Ground, London
2003 Australia India Australia Wanderers, Johannesburg
2007 Australia Sri Lanka West Indies Kensington Oval, Bridgetown
2011 India Sri Lanka India Wankhede Stadium, Mumbai
2015 Australia New Zealand Australia Melbourne Cricket Ground
2019 England New Zealand England Lord’s, London
2023 India

Output sheet – after the program is run:

Output sheet after a program to format cells with a specific word is run.

Program with 2D Array and “NESTED FOR” Loop

This program declares a two dimensional array and initializes data in all its elements.

The first dimension holds the students’ names, and the second dimension holds the “exam results” of the students in the first dimension. These are written back to an Excel sheet. 

Warning: As the code does not select any sheet in specific, please ensure that you keep a blank Excel sheet selected. This can prevent any damage to your existing data.

In case you wish to learn more about multidimensional arrays, please check out this article.

Sub Nested_for_demo2()

'declaring and defining size of an array
'3 means 4 rows starting from 0 to 3 and 1 means 2 columns starting from 0 to 1
Dim arr_stu(1 To 5, 1 To 2) As Variant

'initialize array elements

 arr_stu(1, 1) = "Dave"
 arr_stu(1, 2) = "Fail"
 arr_stu(2, 1) = "Trumpo"
 arr_stu(2, 2) = "Pass"
 arr_stu(3, 1) = "Vincent"
 arr_stu(3, 2) = "Pass"
 arr_stu(4, 1) = "Rose Mary"
 arr_stu(4, 2) = "Pass"
 arr_stu(5, 1) = "Eliza"
 arr_stu(5, 2) = "Fail"
 
' print all elements to the open excel sheet.
For i = 1 To 5
    For j = 1 To 2
        Cells(i, j) = arr_stu(i, j)
    Next j
Next

End Sub

Output of the Program on the Active Excel Sheet: Here 

  1. The rows indicate the “i” value of the array (first dimension) and the iterator variable of the outer “for” loop.
  2. The columns indicate the  “j”  value of the array (Col A – first dimension , Col B – second dimension)  and the iterator variable of the inner “for” loop.

The “Continue” Statement in Visual Basic: Skip a Part of an Iteration

When you encounter a situation where you wish to skip running the rest of the code inside the loop for a specific iteration based on a condition, the “continue” statement will come to your rescue in Visual Basic Programming.

Continue

Syntax:

Continue { Do | For | While }

Where  { Do | For | While } are the respective loops in which it has to be used.

A Simple Example

Sub continue_demo()
' declare a counter
Dim i As Integer

'loop through 10 numbers and print them
For i = 1 To 10
    ' we will skip printing "4"
    If i = 4 Then
        Continue For
    End
    Debug.Print i
Next
End Sub

Your output will not have “4” in this case. As the condition is met in the 4th iteration, the continue statement is hit and the rest of the code is skipped for that iteration. The control then moves to the “next” statement of the loop (inner loop in case of nested loops).  

Note: The Next statement is the closure of a loop, as you may be aware.

Output of the above program

1

2

3

5

6

7

8

9

10

Continue Statement is Not Available in VBA

VBA does not offer the “continue statement” because well-built logic in a loop can help us avoid using a “continue” statement. For example, rearranging statement blocks like nested loops and if conditions can help avoid the use of “continue” statements. 

An Alternative to the Continue Statement

In unavoidable situations, the Goto statement can be used

This article can provide you with more insights on how to properly use the “Goto” statement in VBA.

Conclusion

In my experience, I would say that the “for” loop is my favorite compared to the “do while “/“Do until”/“ For each” loops. The reason is the comfort of defining it completely in one line. Even during run-time, you can find how many iterations are completed and how many are yet to come.

I have also been able to use this loop in situations where I do not know the number of iterations. I manage it using conditions inside the loop. It also comes handy when I want to wait for a page load during automation. Once you start using this loop, you will even start playing around nested “for loops” with much more confidence and fewer of mistakes. 

So, what are you waiting for ? Why not give it a try? 😊

Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь.

Использовать оператор перехода GOTO в приведенном коде
Мне нужен оператор перехода GOTO в программе. Если выводится сообщение «Данное число в массиве.

При вводе пользователем числа от 0 до 9, вывести на экран название программы (использовать оператор goto)
Программу по заданию я написал Написать программу для выполнения следующих действий. При вводе.

Как исполльзовать оператор goto?
Как его юзать?

Как использовать goto?
Я только начал создавать игру «Симулятор бомжа» в консоли и тут я столкнулся с проблемой, как можно.

Оператор GoTo в VBA, ситуации применения GoTo

Оператор GoTo — это оператор безусловного перехода, когда ход выполнения программы без проверки каких-либо условий перепрыгивает на метку в коде. Пример применения GoTo может выглядеть так:

MsgBox «Едем на метро»

EngineNotStarted: — это метка, для нее используется имя (выбираемое по правилам назначения имен для переменных), которое оканчивается на двоеточие.

Иногда использование GoTo очень удобно — например, когда нам нужно добиваться от пользователя ввода правильного значения неизвестное число раз. Однако использование GoTo категорически не рекомендуется, потому что код становится трудночитаемым. Чаще всего GoTo можно заменить на конструкцию Do While или на вызов функции из самой себя.

Работа с циклами

Циклы VBA, конструкция For. Next, конструкция For Each. Next, выход из цикла по Exit For, конструкции Do While и Do Until, выход из цикла по Exit Do, конструкция While. Wend

Циклы используются в ситуациях, когда нам нужно выполнить какое-либо действие несколько раз. Первая ситуация — мы знаем, сколько раз нужно выполнить какое-либо действие, в этом случае используется конструкция For…Next:

For iCounter = 1 to 10

Чтобы указать, насколько должно прирастать значение счетчика, используется ключевое слово Step:

For iCounter = 1 to 10 Step 2

Можно и уменьшать исходное значение счетчика:

For iCounter = 10 to 1 Step -2

Для безусловного выхода из конструкции For…Next используется команда Exit For.

VStop = InputBox (“Введите значение останова”)

For iCounter = 1 to 10

MsgBox «Счетчик: » & iCounter

If iCounter =VInput Then Exit For

Очень часто в VBA требуется сделать какое-нибудь действие со всеми элементам коллекции или массива — перебрать все открытые документы, все листы Excel, все ячейки в определенном диапазоне и т.п. Для того, чтобы пройти циклом по всем элементам коллекции, используется команда For Each … Next:

For Each oWbk in Workbooks

При использовании этого приема можно очень просто найти и получить ссылку на нужный нам объект:

For Each oWbk in Workbooks

Set oMyWorkBook = oWbk

В этом случае мы проходим циклом по всем элементам коллекции Workbooks (то есть открытым рабочим книгам в Excel), для каждой книги проверяем ее имя, и если мы нашли книгу с именем Сводка.xls, то мы получаем на нее ссылку и выходим из цикла. Коллекция рабочих книг — это специальная коллекция, которая умеет производить поиск в себе по имени элементов, поэтому в принципе можно было обойтись такой строкой:

Но для многих других коллекций без конструкции For Each не обойтись.

Еще одна ситуация — когда мы не знаем точно, сколько раз должна быть выполнена та или другая команда — это зависит от какого-либо условия. Используются конструкции Do While…Loop и Do Until…Loop.

Конструкция Do While означает: выполнять какое-либо действие до тех пор, пока условие истинно:

Внимание! Если вы случайно запустили в своей программе бесконечный цикл, нажмите на клавиши +
. Откроется окно, аналогичное представленному на рис. 3.1, в котором вы сможете продолжить выполнение, завершить его или открыть ваш код в отладчике.

Рис. 3.1 Выполнение макроса остановлено по +

Второй вариант — Do Until. Все выглядит точно так же, за одним исключением: цикл будет выполняться до тех пор, пока условие ложно.

Do Until MyVar >= 10

MyVar = MyVar + 1

MsgBox “ MyVar = “ & MyVar

Можно переписать цикл так, чтобы условие проверялось после завершения цикла:

MyVar = MyVar + 1

WScript.Echo “MyVar = “ & MyVar

Loop While MyVar

Дата добавления: 2018-10-27 ; просмотров: 1015 ;

Пример использования Go To

Пример использования Go To

В следующем примере оператор Go To направляет поток программы из главной части процедуры к метке Special Value, если встречается необычное значение:

Function GoToExample (ItemNumber As Integer )

Dim intR As Integer

Select Case ItemNumber

Go To SpecialValue

Case Is = CutOffValue

( операторы, выполняющие какое-то действия)

Обратите внимание на формат метки SpecialValue — она размещается в своей отдельной строке и заканчивается двоеточием. Двоеточие здесь просто обязательно — при его отсутствии VBA непременно расстроится и выведет сообщение об ошибке.

Похожие главы из других книг:

Пример использования слябового распределителя памяти

Пример использования слябового распределителя памяти Давайте рассмотрим пример из реальной жизни, связанный с работой со структурами task_struct (дескрипторы процессов). Показанный ниже код в несколько более сложной форме приведен в файле kernel/fork.c.В ядре определена

Пример использования

Пример использования В следующем примере сервер уведомляет Internet Explorer, что содержание документа не будет меняться в течение 1 часа (pre-check=3600) и что его можно загружать прямо из локального кэша. В случае же изменения страницы, если пользователь запросит ее по истечении 15

4.6. Пример построения диаграммы вариантов использования

4.6. Пример построения диаграммы вариантов использования В качестве примера рассмотрим процесс моделирования системы продажи товаров по каталогу, которая может быть использована при создании соответствующих информационных систем.В качестве актеров данной системы

Простой пример использования сигнала SIGURG

Простой пример использования сигнала SIGURG Теперь мы рассмотрим тривиальный пример отправки и получения внеполосных данных. В листинге 24.1[1] показана программа отправки этих данных.Листинг 24.1. Простая программа отправки внеполосных данных//oob/tcpsend01.c 1 #include «unp.h» 2 int 3 main(int

Простой пример использования функции select

Простой пример использования функции select Теперь мы переделаем код нашего получателя внеполосных данных и вместо сигнала SIGURG будем использовать функцию select. В листинге 24.3 показана принимающая программа.Листинг 24.3. Принимающая программа, в которой (ошибочно)

Пример использования рецептов

Пример использования рецептов Приведенные выше сведения были необходимы для создания общего представления о работе Procmail. В листинге приведен чрезвычайно простой пример файла Procmail, предназначенного для фильтрации сообщений. Содержащиеся в нем рецепты пригодны для

4.5 Пример использования GParted для переразбивки винчестера

4.5 Пример использования GParted для переразбивки винчестера В качестве подопытного кролика я буду использовать такую вот конфигурацию: Рис. 4.3: Пример начальной разметки винчестера. Рис. 4.3: Пример начальной разметки винчестера.Допустим, на первом диске стоит Windows а на

Пример использования парного программирования в одном из проектов

Пример использования парного программирования в одном из проектов Ниже мы приводим цитату из рассказа опытного программиста о том, как его компания впервые попробовала использовать парное программирование. В этом примере упомянуто много основных черт парного

Пример использования Go To

Пример использования Go To В следующем примере оператор Go To направляет поток программы из главной части процедуры к метке Special Value, если встречается необычное значение: Function GoToExample (ItemNumber As Integer ) Dim intR As Integer Select Case ItemNumber Case 2412 Go To SpecialValue Case Is

Пример 9-14. Подстановка параметров и сообщение о «порядке использования»

Пример 9-14. Подстановка параметров и сообщение о «порядке использования» #!/bin/bash# usage-message.sh: $<1?»Порядок использования: $0 ARGUMENT»># Сценарий завершит свою работу здесь, если входные аргументы отсутствуют,#+ со следующим сообщением.# usage-message.sh: 1: Порядок использования: usage-message.sh

1.7.1. Пример использования команды chown

1.7.1. Пример использования команды chown Вот как можно поменять владельца файла с помощью команды chown:$ ls -l-rwxrwxrwx 1 louise admin 345 Sep 20 14:33 project$ chown pauline project $ ls -l-rwxrwxrwx 1 pauline admin 345 Sep 20 14:33 projectПраво владения файлом project переходит от пользователя louise к

1.7.2. Пример использования команды chgrp

1.7.2. Пример использования команды chgrp Следующий пример демонстрирует, как поменять группу, которой принадлежит файл:$ ls -1-rwxrwxrwx 1 pauline admin 345 Sep 20 14:33 project$ chgrp sysadmin project $ ls -1-rwxrwxrwx 1 pauline sysadmin 345 Sep 20 14:33 projectПользователь pauline передал группе sysadmin право владения файлом project, которое до

Оценка статьи:

2 звезды3 звезды4 звезды5 звезд5 звезд

Загрузка…

Adblock
detector

In This Chapter

Discovering methods for controlling the flow of your VBA routines Finding out about the dreaded GoTo statement Using If-Then and Select Case structures Performing looping in your procedures
5ome VBA procedures start at the code’s beginning and progress line by line to the end, never deviating from this top-to-bottom program flow. Macros that you record always work like this. In many cases, however, you need to control the flow of your code by skipping over some statements, executing some statements multiple times, and testing conditions to determine what the procedure does next. Ready or not, you find out how to do all that stuff in this chapter.

Going with the Flow, Dude

Some programming newbies can’t understand how a dumb computer can make intelligent decisions. The secret is in several programming constructs that most programming languages support. Table 10-1 provides a quick summary of these constructs. (I explain all of these later in this chapter.)

Table 10-1 Programming Constructs for Making Decisions
Construct How It Works
GoTo statement Jumps to a particular statement
If-Then structure Does something if something else is true
Select Case Does any of several things, depending on something’s value
For-Next loop Executes a series of statements a specified number of times
Do-While loop Does something as long as something else remains true
Do-Until loop Does something until something else becomes true

The GoTo Statement

A GoTo statement offers the most straightforward means for changing a program’s flow. The GoTo statement simply transfers program control to a new statement, which is preceded by a label.
Your VBA routines can contain as many labels as you like. A label is just a text string followed by a colon. (See Chapter 7 for more label information.)

The following procedure shows how a GoTo statement works:

tmpD-94
The procedure uses the InputBox function to get the user’s name. If the user enters a name other than Bill Gates, the program flow jumps to the WrongName label, displays an apologetic message, and the procedure ends. On the other hand, if Mr. Gates signs on, the procedure displays a welcome message and then executes some additional code (not shown in the example). The Exit Sub statement ends the procedure before the second MsgBox function has a chance to work.
This simple routine works, but VBA provides several better (and more structured) alternatives than GoTo. In general, you should use GoTo only when you have no other way to perform an action. In practice, the only time you really need to use a GoTo statement is for trapping errors. (I cover this in Chapter 12.)
Many hard-core programming types have a deep-seated hatred for GoTo statements because using them tends to result in difficult-to-read “spaghetti code.” Therefore, you should avoid this subject when talking with other programmers.

Decisions, decisions

In this section, I discuss two programming structures that can empower your VBA procedures with some impressive decision-making capabilities: If-Then and Select Case.

The If-Then structure

Okay, I’ll say it: If-Then is VBA’s most important control structure. You’ll probably use this command on a daily basis (at least I do). As in many other aspects of life, effective decision making is the key to success in writing programs. If this topic has the effect I intend, you’ll soon share my philosophy that a successful Excel application boils down to making decisions and acting upon them.

What is structured programming? Does it matter?

If you hang around with programmers, sooner or later you hear the term structured programming. This term has been around for decades, and programmers generally agree that structured programs are superior to unstructured programs. So, what is structured programming? And can you write such things using VBA?
The basic premise of structured programming is that a routine or code segment should have only one entry point and one exit point. In other words, a block of code should be a stand-alone unit. A program cannot jump into the middle of this unit, nor can it exit at any point except the single exit point. When you write structured code, your program progresses in an orderly manner and is easy to follow — unlike a program that jumps around in a haphazard fashion. This pretty much rules out using the GoTo statement.
In general, a structured program is easier to read and understand. More importantly, it’s also easier to modify when the need arises.
VBA is indeed a structured language. It offers standard structured constructs such as If-Then-Else, For-Next loops, Do-Until loops, Do-While loops, and Select Case structures. Furthermore, it fully supports module code constructions. If you’re new to programming, you should try to develop good structure programming habits early on. End of lecture.

The If-Then structure has this basic syntax:

tmp23-1_thumb
Use the If-Then structure when you want to execute one or more statements conditionally. The optional Else clause, if included, lets you execute one or more statements if the condition you’re testing is not true. Sound confusing? Don’t worry; a few examples make this crystal clear.

If-Then examples

The following routine demonstrates the If-Then structure without the optional Else clause:
tmp23-2_thumb
The GreetMe procedure uses VBA’s Time function to get the system time. If the current system time is less than .5 (in other words, before noon), the routine displays a message. If Time is greater than or equal to .5, the routine ends and nothing happens.
To display a different greeting if Time is greater than or equal to .5, add another If-Then statement after the first one:
tmp23-3_thumb
Notice that I used >= (greater than or equal to) for the second If-Then statement. This covers the extremely remote chance that the time is precisely 12:00 p.m.

An If-Then-Else example

Another approach to the preceding problem uses the Else clause. Here’s the same routine recoded to use the If-Then-Else structure:
tmp23-4_thumb
Notice that I use the line continuation character (underscore) in the preceding example. The If-Then-Else statement is actually a single statement. But VBA provides a slightly different way of coding If-Then-Else constructs that use an End If statement. Therefore, the GreetMe procedure can be rewritten as:
tmp23-5_thumb
In fact, you can insert any number of statements under the If part, and any number of statements under the Else part.
What if you need to expand the GreetMe routine to handle three conditions: morning, afternoon, and evening? You have two options: Use three If-Then statements or use a nested If-Then-Else structure. Nesting means placing an If-Then-Else structure within another If-Then-Else structure. The first approach, the three statements, is simplest:
tmp23-6_thumb
The Msg variable gets a different text value, depending on the time of day. The final MsgBox statement displays the greeting: Good Morning, Good Afternoon, or Good Evening.

The following routine performs the same action but uses a nested If-Then-Else structure:

tmp23-7_thumb
The example works fine but could be simplified a bit by omitting the last If-Then part. Because the routine has already tested for two conditions (morning and afternoon), the only remaining condition is evening. Here’s the modified procedure:
tmp23-8_thumb

Using Elself

In both of the previous examples, every statement in the routine is executed — even in the morning. A more efficient structure would exit the routine as soon as a condition is found to be true. In the morning, for example, the procedure should display the Good Morning message and then exit — without evaluating the other superfluous conditions.
With a tiny routine like this, you don’t have to worry about execution speed. But for larger applications in which speed is important, you should know about another syntax for the If-Then structure. The ElseIf syntax follows:
tmp23-9_thumb

Here’s how you can rewrite the GreetMe routine using this syntax:

tmp23-10_thumb
When a condition is true, VBA executes the conditional statements and the If structure ends. In other words, VBA doesn’t waste time evaluating the extraneous conditions, which makes this procedure a bit more efficient than the previous examples. The trade-off (there are always trade-offs) is that the code is more difficult to understand. (Of course, you already knew that.)

Another If-Then example

Here’s another example that uses the simple form of the If-Then structure. This procedure prompts the user for a quantity and then displays the appropriate discount, based on the quantity the user enters:
tmp23-11_thumb
A workbook that contains this section’s examples can be downloaded from this topic’s Web site.
Notice that each If-Then statement in this routine is executed and the value for Discount can change as the statements are executed. However, the routine ultimately displays the correct value for Discount.
The following procedure performs the same tasks by using the alternative ElseIf syntax. In this case, the routine ends immediately after executing the statements for a true condition.
tmp23-12_thumb
Personally, I find these multiple If-Then structures rather cumbersome. I generally use the If-Then structure for only simple binary decisions. When a decision involves three or more choices, the Select Case structure offers a simpler, more efficient approach.

The Select Case structure

The Select Case structure is useful for decisions involving three or more options (although it also works with two options, providing an alternative to the If-Then-Else structure).

The syntax for the Select Case structure follows:

tmp23-13_thumb
Don’t be scared off by this official syntax. Using the Select Case structure is quite easy.

A Select Case example

The following example shows how to use the Select Case structure. This also shows another way to code the examples presented in the previous section:
tmp23-14_thumb
In this example, the Quantity variable is being evaluated. The routine is checking for four different cases (0 to 24, 25 to 49, 50 to 74, and 75 or greater).
Any number of statements can follow each Case statement, and they all are executed if the case is true. If you use only one statement, as in this example, you can put the statement on the same line as the Case keyword, preceded by a colon — the VBA statement separator character. In my opinion, this makes the code more compact and a bit clearer. Here’s how the routine looks using this format:
tmp23-15_thumb
When VBA executes a Select Case structure, the structure is exited as soon as VBA finds a true case.

A nested Select Case example

As demonstrated in the following example, you can nest Select Case structures. This routine examines the active cell and displays a message describing the cell’s contents. Notice that the procedure has three Select Case structures and each has its own End Select statement.
tmp23-16_thumb
This example is available at this topic’s Web site.

The logic goes something like this:

1. Find out whether the cell is empty.
2. If it’s not empty, see whether it contains a formula.
3. If there’s no formula, find out whether it contains a numeric value or text.
When the routine ends, the Msg variable contains a string that describes the cell’s contents. As shown in Figure 10-1, the MsgBox function displays that message.
A message displayed by the Check Cell procedure.
Figure 10-1:
A message displayed by the Check Cell procedure.
You can nest Select Case structures as deeply as you need, but make sure that each Select Case statement has a corresponding End Select statement.
As you can see, indenting makes this potentially confusing code much more understandable. If you don’t believe me, take a look at the same procedure without any indentation:
tmp23-18_thumbtmp23-19_thumb
Fairly incomprehensible, eh?

Knocking Your Code for a Loop

The term looping refers to repeating a block of VBA statements numerous times. You may know how many times your program needs to loop, or variables used in your program’s may determine this.
There are two types of loops: good loops and bad loops. (Good loops get rewarded, and bad loops get sent to their room.)
The following code demonstrates a bad loop. The procedure simply enters consecutive numbers into a range. It starts by prompting the user for two values: a starting value and the total number of cells to fill. (Because InputBox returns a string, I convert the strings to integers by using the CInt function.) This loop uses the GoTo statement to control the flow. The Cell Count variable keeps track of how many cells are filled. If this value is less than the number requested by the user, program control loops back to Do Another.
tmp23-20_thumb
This routine works as intended, so why is it an example of bad looping? As I mention earlier in this chapter, avoid using a GoTo statement unless it’s absolutely necessary. Using GoTo statements to perform looping
Is contrary to the concept of structured programming. (See the sidebar earlier in this chapter, “What is structured programming? Does it matter?”)
Makes the code more difficult to read.
Is more prone to errors than using structured looping procedures.
VBA has enough structured looping commands that you almost never have to rely on GoTo statements for your decision making. Again, the exception is for error handling.
Now you can move on to a discussion of good looping structures.

For-Next loops

The simplest type of loop is a For-Next loop. Here’s the syntax for this structure:
tmp23-21_thumb
The looping is controlled by a counter variable, which starts at one value and stops at another value. The statements between the For statement and the Next statement are the statements that get repeated in the loop. To see how this works, keep reading.

A For-Next example

The following example shows a For-Next loop that doesn’t use the optional Step value or the optional Exit For statement. This routine loops 100 times and uses the VBA Rnd function to enter a random number into 100 cells:
tmp23-22_thumb
In this example, Count (the loop counter variable) starts with a value of 1 and increases by 1 each time through the loop. Because I didn’t specify a Step value, VBA uses the default value (1). The Offset method uses the value of
Count as an argument. The first time through the loop, the procedure enters a number into the active cell offset by zero rows. The second time through (Count = 2), the procedure enters a number into the active cell offset by one row (Count -1), and so on.
Because the loop counter is a normal variable, you can change its value within the block of code between the For and the Next statements. This, however, is a very bad practice. Changing the counter within the loop can have unpredictable results. Take special precautions to ensure that your code does not directly change the value of the loop counter.

A For-Next example with a Step

You can use a Step value to skip some values in a For-Next loop. Here’s the same procedure as in the preceding section, rewritten to insert random numbers into every other cell:
tmp23-23_thumb
This time, Count starts out as 1 and then takes on a value of 3, 5, 7, and so on. The final Count value is 99. The Step value determines how the counter is incremented.
This chapter introduces looping via the BadLoop example, which uses a GoTo statement. Here’s the same example, which is available on this topics Web site, converted into a good loop by using the For-Next structure:
tmp23-24_thumb

A For-Next example with an Exit For statement

A For-Next loop can also include one or more Exit For statements within the loop. When VBA encounters this statement, the loop terminates immediately.
The following example, available on the topics Web site, demonstrates the Exit For statement. This routine identifies which of the active worksheet’s cells in column A has the largest value:
tmp23-25_thumb
The routine calculates the maximum value in the column by using Excel’s MAX function and assigns the result to the MaxVal variable. The For-Next loop then checks each cell in the column. If the cell being checked is equal to MaxVal, the routine doesn’t need to continue looping (its job is finished), so the Exit For statement terminates the loop. Before terminating the loop, the procedure activates the cell with the maximum value and informs the user of its location.

A nested For-Next example

So far, all this chapter’s examples use relatively simple loops. However, you can have any number of statements in the loop and nest For-Next loops inside other For-Next loops.
The following example uses a nested For-Next loop to insert random numbers into a 12-row-by-5-column range of cells, as shown in Figure 10-2. Notice that the routine executes the inner loop (the loop with the Row counter) once for each iteration of the outer loop (the loop with the Col counter). In other words, the routine executes the Cells(Row, Col) = Rnd statement 60 times.
tmp23-26_thumb
These cells were filled using a nested For-Next loop.
Figure 10-2:
These cells were filled using a nested For-Next loop.
The next example uses nested For-Next loops to initialize a three-dimensional array with zeros. This routine executes the statement in the middle of all the loops (the assignment statement) 1,000 times, each time with a different combination of values for i, j, and k:
tmp23-28_thumb
Refer to Chapter 7 for information about arrays.

Do-While loop

VBA supports another type of looping structure known as a Do-While loop. Unlike a For-Next loop, a Do-While loop continues until a specified condition is met. Here’s the Do-While loop syntax:
tmp23-29_thumb
The following example uses a Do-While loop. This routine uses the active cell as a starting point and then travels down the column, multiplying each cell’s value by 2. The loop continues until the routine encounters an empty cell.
tmp23-30_thumb
Some people prefer to code a Do-While loop as a Do-Loop While loop. This example performs exactly as the previous procedure but uses a different loop syntax:
tmp23-31_thumb
Remember this key difference between the Do-While and Do-Loop While loops: The Do-While loop always performs its conditional test first. If the test is not true, the instructions inside the loop are never executed. The Do-Loop While loop, on the other hand, always performs its conditional test after the instructions inside the loop are executed. Thus, the loop instructions are always executed at least once, regardless of the test. This difference can make a profound difference in how your program functions.

Do-Until loop

The Do-Until loop structure is similar to the Do-While structure. The two structures differ in their handling of the tested condition. A program continues to execute a Do-While loop while the condition remains true. In a Do-Until loop, the program executes the loop until the condition is true.

Here’s the Do-Until syntax:

tmp23-32_thumb
The following example is the same one presented for the Do-While loop but recoded to use a Do-Until loop:
tmp23-33_thumb
You may encounter a different form of the Do-Until loop — a Do-Loop Until loop. The following example, which has the same effect as the preceding procedure, demonstrates an alternate syntax for this type of loop:
tmp23-34_thumb
There is a subtle difference in how the Do-Until loop and the Do-Loop Until loop operate. In the former, the test is performed at the beginning of the loop, before anything in the body of the loop is executed. This means that it is possible that the code in the loop body will not be executed if the test condition is met. In the latter version, the condition is tested at the end of the loop. This means, at a minimum, the Do-Loop Until loop always results in the body of the loop being executed once.

Looping through a Collection

VBA supports yet another type of looping — looping through each object in a collection. Recall that a collection consists of a number of the same type of object. For example, each workbook has a collection of worksheets (the Worksheets collection), and Excel has a collection of all open workbooks (the Workbooks collection).
When you need to loop through each object in a collection, use the For Each-Next structure. The syntax is
tmp23-35_thumb
The following example loops through each worksheet in the active workbook and deletes the first row of each worksheet:
tmp23-36_thumb
In this example, the variable WkSht is an object variable that represents each worksheet in the workbook. Nothing is special about the variable name WkSht — you can use any variable name that you like.
The example that follows loops through the cells in a range, checking each one. The code switches the sign of the values (negative values are made positive; positive values are made negative). It does this by multiplying each value times -1. Note that I used an If-Then construct, along with the VBA Is Numeric function, to ensure that the cell contains a numeric value:
tmp23-37_thumb
Here’s another example that loops through each chart on Sheet1 (that is, each member of the Chart Objects collection) and changes each chart to a line chart. In this example, Cht is a variable that represents each Chart Object. If Sheetl has no Chart Objects, nothing happens.

tmp23-38_thumb

How can I jump to another part of the VBA program? This can be done by using the GOTO statement. GOTO can also be used to make a loop when combined to a conditional statement like IF. This is an easy tutorial to Microsoft Excel».

Let’s do scan through a row or a range and calculate the
square of all the items in the range. The range will finish with the word
end. Of course you can end it with something else or just detect the first
empty cell.

vba scan defined range and square

You can see in the next code the GOTO statement and the
FLAGS associated with this GOTO statement. Here they are called BEGINNING:
and END:

Sub square_Range()

Dim myWS As Worksheet
Set myWS =
ThisWorkbook.ActiveSheet

i = 2 ‘ counter
Beginning:                                
‘ flag for the start of the GOTO loop

i = i + 1
Value =
myWS.Range(Cells(3, i), Cells(3, i)).Value
If Value = «» Or Value =
«end» Or i > 100 Or IsNumeric(Value) = False Then GoTo Out
                       
‘ this statement test if the value is a numerical value, but also makes
sure that we get out of the loop
                       
‘ when i is bigger than 100. This is a safety you can implement or not
in a loop if you wish.

square = Value * Value
myWS.Range(Cells(5,
i), Cells(5, i)).Value = square

GoTo Beginning                    
‘ we go back to the beginning of the loop

Out:                                    
‘ this is the exit road of the GOTO Loop statement
i = i — 3                             
‘ setting i to the real value as we started in the second column
Cells(7, 3).Value = «we have squared all the » & i & » values in your
table»

End Sub

This is how the code could look like.

Beware, with the GOTO statement, not to have an endless loop.
Once you are stuck in such a loop, you will have to do CTRL-ALT-DELETE to
stop Excel because it will be stuck in a loop. There are different ways to
make sure you get out of the loop is to use the IF THEN statement to stop
the loop after a certain number of loops have been done, you can use a timer
or the now() funtion
that counts the time the program is in the loop.

vba scan defined range and square

Congratulation, you made it until the end of this VBA Code
Example.

Понравилась статья? Поделить с друзьями:
  • Vba excel google chrome
  • Vba excel get range address
  • Vba excel get hyperlink
  • Vba excel get all rows
  • Vba excel function пример