ТРЕНИНГИ
Быстрый старт
Расширенный Excel
Мастер Формул
Прогнозирование
Визуализация
Макросы на VBA
КНИГИ
Готовые решения
Мастер Формул
Скульптор данных
ВИДЕОУРОКИ
Бизнес-анализ
Выпадающие списки
Даты и время
Диаграммы
Диапазоны
Дубликаты
Защита данных
Интернет, email
Книги, листы
Макросы
Сводные таблицы
Текст
Форматирование
Функции
Всякое
Коротко
Подробно
Версии
Вопрос-Ответ
Скачать
Купить
ПРОЕКТЫ
ОНЛАЙН-КУРСЫ
ФОРУМ
Excel
Работа
PLEX
© Николай Павлов, Planetaexcel, 2006-2022
info@planetaexcel.ru
Использование любых материалов сайта допускается строго с указанием прямой ссылки на источник, упоминанием названия сайта, имени автора и неизменности исходного текста и иллюстраций.
Техническая поддержка сайта
ООО «Планета Эксел» ИНН 7735603520 ОГРН 1147746834949 |
ИП Павлов Николай Владимирович ИНН 633015842586 ОГРНИП 310633031600071 |
The “Next Without For” Compile Error is a very common compile-time error in Excel VBA. It implies that a Next statement must always have a preceding For statement that matches it. If a Next statement is used without a corresponding For statement, this error is generated.
Let us look at some most common causes of the error and way to fix and avoid them.
Example 1: If statement without a corresponding “End If” statement
Sub noEndIf() Dim rng As Range Dim cell As Range Set rng = ActiveSheet.Range("B1:B10") For Each cell In rng If cell.Value = 0 Then cell.Interior.color = vbRed Else cell.Interior.color = vbGreen Next cell End SubEvery If statement (and If Else Statement) must have a corresponding End If statement along with it. As you can see in the above code, End If is missing after the Else block, causing the error. The right way to do it is
Sub withEndIf() Dim rng As Range Dim cell As Range Set rng = ActiveSheet.Range("B1:B10") For Each cell In rng If cell.Value = 0 Then cell.Interior.color = vbRed Else cell.Interior.color = vbGreen End If Next cell End SubExample 2: Incorrect sequence of End If and Next statements
Sub incorrectEndIf() Dim rng As Range Dim cell As Range Set rng = ActiveSheet.Range("B1:B10") For Each cell In rng If cell.Value = 0 Then cell.Interior.color = vbRed Else cell.Interior.color = vbGreen Next cell End If End SubHere, the End If statement is not placed correctly causing overlapping as shown below:
For
If
Next
End IfThe entire If statement (including, If, Else and End If statements), must be placed withing the For…Next block as shown below
Sub correctEndIf() Dim rng As Range Dim cell As Range Set rng = ActiveSheet.Range("B1:B10") For Each cell In rng If cell.Value = 0 Then cell.Interior.color = vbRed Else cell.Interior.color = vbGreen End If Next cell End SubExample 3: With statement has a corresponding End With Statement missing
Sub noEndWith() Dim counter As Integer Dim lastRow As Integer Dim fName As String, lName As String, fullName As String lastRow = 10 For counter = 1 To lastRow With ActiveSheet fName = .Cells(counter, 1).Value lName = .Cells(counter, 2).Value fullName = fName & " " lName 'Further processing here Next counter End SubJust like an If statement, the With statement should also have a corresponding End With statement, without which error will be thrown. The working example:
Sub withEndWith() Dim counter As Integer Dim lastRow As Integer Dim fName As String, lName As String, fullName As String lastRow = 10 For counter = 1 To lastRow With ActiveSheet fName = .Cells(counter, 1).Value lName = .Cells(counter, 2).Value End With fullName = fName " " lName 'Further processing here Next counter End SubExample 4: Overlapping For and If Else statement
Say, in the example below, you want to do some processing only if a condition is false. Else you want to continue with the next counter of the For loop
Sub overlapping() Dim counter As Integer For counter = 1 To 10 If Cells(counter, 1).Value = 0 Then Next counter Else 'Do the processing here End If Next counter End SubNote: as in other programming languages, VBA does not have a continue option for a loop. When the control of the program reaches the first “Next counter” statement after the If statement — it finds that there is a Next statement within the If statement. However, there is no corresponding For statement within this If Block. Hence, the error.
So, you can use one of the two solutions below:
Simply remove the “next” statement after If
Sub solution1() Dim counter As Integer For counter = 1 To 10 If Cells(counter, 1).Value = 0 Then 'Simply don't do anything here Else 'Do the processing here End If Next counter End SubOR
Not the if condition and place your code there. Else condition is not required at all
Sub solution2() Dim counter As Integer For counter = 1 To 10 If Not Cells(counter, 1).Value = 0 Then 'Not the if condition and 'Do the processing here End If Next counter End SubThe bottom line is that the “If, Else, End If statement block” must be completely within the For loop.
Avoiding the Next without For error by using standard coding practices
The best way to avoid this error is to follow some standard practices while coding.
1. Code indentation: Indenting your code not only makes it more readable, but it helps you identify if a loop / if statement / with statement are not closed properly or if they are overlapping. Each of your If statements should align with an End If, each For statement with a Next, each With statement with an End With and each Select statement with an End Select
2. Use variable name with Next: Though the loop variable name is not needed with a next statement, it is a good practice to mention it with the Next statement.
So, change
Nextto
Next counterThis is particularly useful when you have a large number of nested for Loops.
3. As soon as you start a loop, write the corresponding end statement immediately. After that you can code the remaining statements within these two start and end statements (after increasing the indentation by one level).
If you follow these best practices, it is possible to completely and very easily avoid this error in most cases.
See also: Compile Error: Expected End of Statement
Permalink
Cannot retrieve contributors at this time
title | keywords | f1_keywords | ms.prod | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|
Next without For |
vblr6.chm1011227 |
vblr6.chm1011227 |
office |
304e0911-95b7-93e5-79dd-d2ceaaceddd1 |
06/08/2017 |
medium |
A Next statement must have a preceding For statement that matches. This error has the following cause and solution:
- A Next statement is used without a corresponding For statement. Check other control structures within the For…Next structure and verify that they are correctly matched. For example, an If without a matching End If inside the For…Next structure generates this error.
For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).
[!includeSupport and feedback]
-
#1
I’m puzzled on this as I do not understand where the error is comming from.
I have a macro that is pulling information between worksheets, but the For Next statements appear clean. However, when I run, I get the [Compile Error: Next without For] message
Condensed Example
‘Let’s say we have (4) worksheets within the workbook
ShtNum = Sheets.Count
‘ We’ll start pulling data off Sheet2 to start
For Loop1 = 2 to ShtNum
Sheets(Loop1).Select
Sheets(Loop1).Activate
‘ Let’s get some data
Set d = Cells.find(What:=»Created», LookAt:=xlWhole)
CrtDate = Cells(2, d.Column)
‘ Switch back to the 1st sheet and place the data in specific areas.
Sheets(1).Select
Sheets(1).Activate
Cells(3, 2) = CrtDate
Selection.NumberFormat = «mm/dd/yyyy»
‘go Color the Cells
GoSub colorbrtyel
‘ Get additional Data on other sheets.
‘ Return back to Sheet1 and place the data.
‘do a small loop within a Loop
for I= 2 to last row
‘format cells
next I
‘ do some gosubs to format the data.
Sheets(Loop1).Select
Sheets(Loop1).Activate
Next Loop1
‘————————————————-
Waterfall charts in Excel?
Office 365 customers have access to Waterfall charts since late 2016. They were added to Excel 2019.
-
#2
Just at quick glance: last row has a space
-
#3
Hello,
The Loop near the top, Loop1 is missing Next Loop1.
Where ever you need the loop to happen in you code, Place Next Loop1.
-Jeff
-
#4
Just at quick glance: last row has a space
that was a typo to show the smaller for-next-loop within the for-next-loop.
-
#5
Hello,
The Loop near the top, Loop1 is missing Next Loop1.
Where ever you need the loop to happen in you code, Place Next Loop1.
-Jeff
Jeff, the Next Loop1 is at the bottom.
ie:
For Loop1 = 2 to ShtNum
gosub 1
gosub 2
for I= 2 to lastrow
next I
Next Loop1
‘continue program
‘1
return
exit sub
‘2
return
exit sub
end Sub
-
#6
Why do you have Gosub in the code?
I can’t remember the last time I saw that used in any code and don’t think I’ve ever seen it in VBA.
It might even be what’s causing the problem, especially if it causes the code to leap out of the loop.
shg
MrExcel MVP
-
#7
Here’s some code that compiles so you can step through it:
Code:
Sub x()
Dim ShtNum As Long
Dim Loop1 As Long
Dim lastrow As Long
Dim i As Long
ShtNum = 3
lastrow = 4
For Loop1 = 2 To ShtNum
GoSub 1
GoSub 2
For i = 2 To lastrow
Next i
Next Loop1
' other code
Exit Sub
1
Return
2
Return
End Sub
-
#8
Issue Resolved.
Discovered a misplaced «With Selection.Interior» statement embedded within all of the code. but I’m not sure how it triggered the «Next without For» error.
Thanks for all of your help.
-
#9
If it didn’t have a End With it would trigger an error.
If there were no loops in the code you would get a message specific to With/End With.
Макрос останавливается с ошибкой Next без For |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |