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.
Contents
- Example 1: If statement without a corresponding “End If” statement
- Example 2: Incorrect sequence of End If and Next statements
- Example 3: With statement has a corresponding End With Statement missing
- Example 4: Overlapping For and If Else statement
- Avoiding the Next without For error by using standard coding practices
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
ТРЕНИНГИ
Быстрый старт
Расширенный Excel
Мастер Формул
Прогнозирование
Визуализация
Макросы на VBA
КНИГИ
Готовые решения
Мастер Формул
Скульптор данных
ВИДЕОУРОКИ
Бизнес-анализ
Выпадающие списки
Даты и время
Диаграммы
Диапазоны
Дубликаты
Защита данных
Интернет, email
Книги, листы
Макросы
Сводные таблицы
Текст
Форматирование
Функции
Всякое
Коротко
Подробно
Версии
Вопрос-Ответ
Скачать
Купить
ПРОЕКТЫ
ОНЛАЙН-КУРСЫ
ФОРУМ
Excel
Работа
PLEX
© Николай Павлов, Planetaexcel, 2006-2022
info@planetaexcel.ru
Использование любых материалов сайта допускается строго с указанием прямой ссылки на источник, упоминанием названия сайта, имени автора и неизменности исходного текста и иллюстраций.
Техническая поддержка сайта
ООО «Планета Эксел» ИНН 7735603520 ОГРН 1147746834949 |
ИП Павлов Николай Владимирович ИНН 633015842586 ОГРНИП 310633031600071 |
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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 |
Sub tt() Dim cost() '(10) As Double Dim amount() '(10, 5) As Integer Dim pay(8) As Double Dim amount_n(10) As Integer Dim day As Integer Dim sumpay As Double Dim m As Integer, p As Integer Dim firma(), repaired() Dim min_repaired As Integer, min_repaired_n As Integer 'firma = [a4:a13].Value 'min_repaired = 32767 'For m = 1 To 10 'amount_n(m) = 0 ' 'Next 'For p = 1 To 8 ' ' pay(p) = 0 ' 'Next sumpay = 0 day = 0 ' Sheets("Start").Select cost = [b4:b13].Value ' For m = 1 To 10 ' ' cost(m) = Cells(3 + m, 2) ' ' Next amount = [c4:i13].Value 'For m = 1 To 10 ' ' For p = 1 To 7 ' ' amount(m, p) = Cells(3 + m, 2 + p) ' ' Next p ' 'Next m Sheets("Results").Select Cells(2, 1) = " Íàèìåíîâàíèå òåëåâèçîðà " Cells(2, 3) = " Êîë-âî îòðåìîíòèðîâàííûõ òåëåâèçàðîâ çà íåäåëþ " Cells(3, 3) = " 1-é äåíü " Cells(3, 4) = " 2-é äåíü " Cells(3, 5) = " 3-é äåíü " Cells(3, 6) = " 4-é äåíü " Cells(3, 7) = " 5-é äåíü " Cells(3, 8) = " 6-é äåíü " Cells(3, 9) = " 7-é äåíü " Cells(3, 10) = " Âñåãî " Cells(4, 1) = "ñàìñóíã" Cells(5, 1) = "ôèëèïñ" Cells(6, 1) = "ñîíè" Cells(7, 1) = "àéñåð" Cells(8, 1) = "øàðï" Cells(9, 1) = "ëäæè" Cells(10, 1) = "âèòÿçü" Cells(11, 1) = "õï" Cells(12, 1) = "çàíóñè" Cells(13, 1) = "óðàë" For m = 1 To 10 For p = 1 To 7 Cells(3 + m, 2 + p) = amount(m, p) amount_n(m) = amount_n(m) + amount(m, p) Next p Cells(3 + m, 10) = amount_n(m) Next m Cells(15, 1) = " Íàèìåíîâàíèå òåëåâèçîðà " Cells(15, 2) = " Ñòîèìîñòü ðàáîò " Cells(15, 3) = " Çàðàáîòîê ìàñòåðà çà êàæäûé äåíü " Cells(16, 3) = " 1-é äåíü " Cells(16, 4) = " 2-é äåíü " Cells(16, 5) = " 3-é äåíü " Cells(16, 6) = " 4-é äåíü " Cells(16, 7) = " 5-é äåíü " Cells(16, 8) = " 6-é äåíü " Cells(16, 9) = " 7-é äåíü " Cells(16, 10) = " Âñåãî " Cells(17, 1) = " Ñàìñóíã " Cells(18, 1) = " ôèëèïñ " Cells(19, 1) = " ñîíè " Cells(20, 1) = " àéñåð " Cells(21, 1) = " øàðï " Cells(22, 1) = " ëäæè " Cells(23, 1) = " âèòÿçü " Cells(24, 1) = " õï " Cells(25, 1) = " çàíóñè " Cells(26, 1) = " óðàë " For m = 1 To 10 For p = 1 To 7 Cells(16 + m, 2 + p) = amount(m, p) * cost(m, 1) pay(p) = pay(p) + amount(m, p) * cost(m, 1) pay(8) = pay(8) + amount(m, p) * cost(m, 1) Next p Cells(16 + m, 2) = cost(m, 1) Cells(16 + m, 10) = cost(m, 1) * amount_n(m) Next m For p = 1 To 7 Cells(27, 2 + p) = pay(p) If pay(p) > sumpay Then sumpay = pay(p) day = p End If Next Cells(27, 10) = pay(8) Cells(28, 1) = " Çàðàáîòîê ìàñòåðà çà íåäåëþ " Cells(28, 5) = pay(8) Cells(29, 1) = "Äåíü ñ ìàêñèìàëüíûì çàðàáîòêîì" Cells(29, 5) = day Cells(29, 6) = " Çàðàáîòàíî " Cells(29, 8) = sumpay Cells(30, 1) = " производитель телевизора, наименьшего количество которого было отремонтировано за неделю" For p = LBound(repaired) To UBound(repaired) If repaired(p, 1) < min_repaired Then min_repaired = repaired(p, 1) min_repaired_n = p End If Next p Cells(30, 10) = firma(min_repaired_n, 1) End Sub |
|
|
-
#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
‘————————————————-
Excel Wisdom
Using a mouse in Excel is the work equivalent of wearing a lanyard when you first get to college
-
#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.
-
09-29-2021, 11:13 AM
#1
Registered User
Compile Error: Next without For
Hi All,
Can’t seem to figure out why my code isn’t working! The code is suppose to cycle through sheets 2 to 5, and first check if there is anything in cell D14. If nothing is populated in cell D14, then it should move on to the next sheet. If there IS something populated in D14, then the code should continue to populate the simply Vlookup formula in column AN. Thoughts?
Thanks!
‘ Sales_Stage_Definition_Formula Macro
‘Application.ScreenUpdating = False
With ActiveWorkbook
For i = 2 To 5
Sheets(i).ActivateIf Range(«D14») = «» Then
Next i
End IfRange(«AN14»).Select
ActiveCell.FormulaR1C1 = «=VLOOKUP(RC[-1],’Sales Stage’!R2C2:R12C5,3,FALSE)»
Selection.AutoFill Destination:=Range(«AN14:AN» & Range(«D» & Rows.Count).End(xlUp).Row)
Range(Selection, Selection.End(xlDown)).SelectNext i
End With
Worksheets(«Instructions»).Activate
Application.ScreenUpdating = True
End Sub
Last edited by knykil; 09-29-2021 at 12:03 PM.
-
09-29-2021, 11:20 AM
#2
Re: Compile Error: Next without For
Untested as no sample file…
Good Luck
I don’t presume to know what I am doing, however, just like you, I too started somewhere…
One-day, One-problem at a time!!!
If you feel I have helped, please click on the star to left of post [Add Reputation]
Also….add a comment if you like!!!!
And remember…Mark Thread as Solved.
Excel Forum Rocks!!!
-
09-29-2021, 11:55 AM
#3
Re: Compile Error: Next without For
-
09-29-2021, 11:58 AM
#4
Re: Compile Error: Next without For
You have one For i = 2 To 5 but two Next i statements. Hence one of them is missing a For. You can’t have two statements jumping back to the same For.
Trevor Shuttleworth — Excel Aid
I dream of a better world where chickens can cross the road without having their motives questioned
‘Being unapologetic means never having to say you’re sorry’ John Cooper Clarke
-
09-29-2021, 12:05 PM
#5
Registered User
Re: Compile Error: Next without For
All — Thank you for your feedback. I’ve since added an example file. The idea is that the ‘J MFI’ tab should be skipped, while tabs 2, 3 and 5 should have the formula populated in column AN. Being relatively new to VBA, i’m not exactly sure where to put the second FOR statement.
Thanks.
-
09-29-2021, 12:37 PM
#6
Re: Compile Error: Next without For
Surely sales stage should be skipped as well
-
09-29-2021, 01:12 PM
#7
Registered User
Re: Compile Error: Next without For
Originally Posted by sintek
Surely sales stage should be skipped as well
Sintek — Thanks for the response! Unfortunately, this won’t apply to my situation. The example file is a slim down version of the master file. Each month, there could be different tabs that don’t have any data. Therefore, I cannot specify which tabs to skip over. It needs to run dynamically. Ultimately it will run through tabs 2-26 in the master file. Thoughts?
-
09-29-2021, 01:55 PM
#8
Registered User
Re: Compile Error: Next without For
Originally Posted by TMS
You have one For i = 2 To 5 but two Next i statements. Hence one of them is missing a For. You can’t have two statements jumping back to the same For.
TMS, i’ve since added an example file. I’m not too familiar with VBA, can you spell it out?
-
09-29-2021, 01:56 PM
#9
Registered User
Re: Compile Error: Next without For
Originally Posted by rorya
Rorya — I’ve since added an excel example. I’m new to VBA, could you spell it out for me?
-
09-29-2021, 03:11 PM
#10
Re: Compile Error: Next without For
So then back to initial solution provided skipping «J MFI» tab
-
09-30-2021, 07:39 AM
#11
Registered User
Re: Compile Error: Next without For
Originally Posted by sintek
So then back to initial solution provided skipping «J MFI» tab
Sintek — Thanks again for the response. I really do appreciate your help. However, with the skip tabs changing each month, I can not call out a specific tab in the code because the next month the J MFI tab could very well have data in it. Thoughts?
-
09-30-2021, 07:45 AM
#12
Re: Compile Error: Next without For
You are not being transparent with your requirement…What sheets are you actually wanting to loop and what are you actually wanting to skip?
You first stated you want to loop shhets and only if D14 has no value then do something…
Then you say that you want to skip Tab «J MFI»
Now you say, you don’t know what the tab is going to be…Ultimately it will run through tabs 2-26 in the master file
So just loop 2 to 26????
Also…No need to quote entire posts…it just clutters the thread…
Last edited by sintek; 09-30-2021 at 07:49 AM.
-
09-30-2021, 07:56 AM
#13
Re: Compile Error: Next without For
-
09-30-2021, 08:06 AM
#14
Registered User
Re: Compile Error: Next without For
Rorya — spot on! Thank you so much for your help! Cheers!
-
09-30-2021, 08:08 AM
#15
Registered User
Re: Compile Error: Next without For
Sintek — I apologize for the confusion. I suppose truncating the file did insert ambiguity into my explanation/description. I appreciate your patience and assistance. It seems that Rorya was able to provide to desired solution. Cheers.
-
09-30-2021, 08:13 AM
#16
Re: Compile Error: Next without For
Oh my Gosh…I give up…Post 2 does just that…
Time for a Forum Break…Happy Coding Guys…I’m outta here…
-
09-30-2021, 08:42 AM
#17
Re: Compile Error: Next without For
Recommended to ease the mental pain — «2020 Arabella Merlot» wish it was readily available in the UK at SA prices (�3.40/bottle)
Torachan,
Mission statement; Promote the use of Tables, Outlaw the use of ‘merged cells’ and ‘RowSource’.
-
09-30-2021, 09:04 AM
#18
Re: Compile Error: Next without For