Compile error next without for

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

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 Sub

Every 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 Sub

Example 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 Sub

Here, the End If statement is not placed correctly causing overlapping as shown below:

For
If
Next
End If

The 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 Sub

Example 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 Sub

Just 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 Sub

Example 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 Sub

Note: 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 Sub

OR

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 Sub

The 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

 Next 

to

 Next counter 

This 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
   Книги, листы
   Макросы
   Сводные таблицы
   Текст
   Форматирование
   Функции
   Всякое
PLEX

   Коротко
   Подробно
   Версии
   Вопрос-Ответ
   Скачать
   Купить

ПРОЕКТЫ

ОНЛАЙН-КУРСЫ

ФОРУМ

   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
  • Home
  • VBForums
  • Visual Basic
  • Office Development
  • Compile Error: Next without For

  1. May 5th, 2005, 08:25 AM


    #1

    neilma is offline

    Thread Starter


    New Member


    Compile Error: Next without For

    Hi,

    I am a novice at this and would appreciate any help.
    I get a Compile Error: Next without For message even though I do have a For. Here’s the script:

    Dim myOscArray(10, 3) As Single
    Dim mySumflow As Single
    Dim myMeanflow As Single
    mySumflow = 0
    j = 0
    Set currentCell = Range(«I11»)
    For i = 1 To myDatasecs — 2
    Set nextCell = currentCell.Offset(1, 0)
    Set currentCell = nextCell
    mySumflow = mySumflow + currentCell.Offset(0, -2).Value
    If j = 11 Then
    myMeanflow = mySumflow / i
    Exit For
    Else
    If currentCell.Formula <> «» Then
    myOscArray(j, 1) = currentCell.Value
    Else
    If currentCell.Offset(0, 1).Value <> «» Then
    myOscArray(j, 2) = currentCell.Value
    j = j + 1
    Else
    Next i

    Thanks,
    Neil


  2. May 5th, 2005, 08:42 AM


    #2

    Re: Compile Error: Next without For

    Quote Originally Posted by neilma

    Hi,

    Code:

        Dim myOscArray(10, 3) As Single
        Dim mySumflow As Single
        Dim myMeanflow As Single
    
        mySumflow = 0
        j = 0
        Set currentCell = Range("I11")
    
        For i = 1 To myDatasecs - 2
            Set nextCell = currentCell.Offset(1, 0)
            Set currentCell = nextCell
            mySumflow = mySumflow + currentCell.Offset(0, -2).Value
            If j = 11 Then
                myMeanflow = mySumflow / i
                Exit For
            Else
                If currentCell.Formula <> "" Then
                    myOscArray(j, 1) = currentCell.Value
                Else
                    If currentCell.Offset(0, 1).Value <> "" Then
                        myOscArray(j, 2) = currentCell.Value
                        j = j + 1
                    Else
               End if
            end if
        Next i

    You forgot to close your if statements

    Feeling like a fly on the inside of a closed window (Thunk!)
    If I post a lot, it is because I am bored at work! ;D Or stuck…
    * Anything I post can be only my opinion. Advice etc is up to you to persue…


  3. May 5th, 2005, 11:52 AM


    #3

    neilma is offline

    Thread Starter


    New Member


    Re: Compile Error: Next without For

    Thanks for the help.
    I guess it’s obvious that I don’t know what I’m doing.

    I have another problem, but I’ll post it on another thread since it doesn’t fit this title.

    Thanks.
    Neil


  4. Aug 19th, 2009, 02:27 PM


    #4

    anoble1 is offline


    New Member


    Re: Compile Error: Next without For

    I am having trouble with a piece of code I recently wrote. It is coming up with a compile error: next without For.
    Thanks!!!

    While Not records.EOF
    For i = 0 To 6
    If i = 5 Then
    i = 8
    ElseIf i = 6 Then
    i = 11

    If isPlanLocked(records!Year, i) Then
    Forms!frmMain!frameDivision.value = i
    DoCmd.OpenForm «frmPlan»
    Forms!frmPlan!txtYear.value = records!Year
    DoCmd.OpenForm «frmPrintPlan»
    PrintPlan
    DoCmd.OutputTo acOutputReport, «rptPlan», «Snapshot Format», path & Forms!frmPlan!txtYear.value & » » & FindDivisionName(Forms!frmMain!frameDivision.value) & «.snp»
    DoCmd.Close acReport, «rptPlan»
    DoCmd.Close acForm, «frmPrintPlan»
    DoCmd.Close acForm, «frmPlan»
    End If

    records.MoveNext
    Next i
    Wend
    records.Close


  5. Aug 19th, 2009, 02:45 PM


    #5

    Re: Compile Error: Next without For

    The error is because you are missing an End If. See below…

    vb Code:

    1. While Not records.EOF

    2.     For i = 0 To 6

    3.         If i = 5 Then

    4.             i = 8

    5.         ElseIf i = 6 Then

    6.             i = 11

    7.         End If '<~~~ YOU ARE MISSING THIS

    8.         If isPlanLocked(records!Year, i) Then

    9.             Forms!frmMain!frameDivision.Value = i

    10.             DoCmd.OpenForm "frmPlan"

    11.             Forms!frmPlan!txtYear.Value = records!Year

    12.             DoCmd.OpenForm "frmPrintPlan"

    13.             PrintPlan

    14.             DoCmd.OutputTo acOutputReport, "rptPlan", _

    15.             "Snapshot Format", Path & Forms!frmPlan!txtYear.Value & _

    16.             " " & FindDivisionName(Forms!frmMain!frameDivision.Value) & ".snp"

    17.             DoCmd.Close acReport, "rptPlan"

    18.             DoCmd.Close acForm, "frmPrintPlan"

    19.             DoCmd.Close acForm, "frmPlan"

    20.         End If

    21.         records.MoveNext

    22.     Next i

    23. Wend

    24. records.Close

    Tip: If you arrange your code like the way I did, then it is always easier to read them and keep a track of your ifs,endif’s,for,next etc…

    A good exercise for the Heart is to bend down and help another up…
    Please Mark your Thread «Resolved», if the query is solved

    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27″ 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero


  6. Aug 19th, 2009, 02:46 PM


    #6

    Re: Compile Error: Next without For

    1) even though it’s semi-related… it would have been better to start a new thread than to dredge up a 4 year old one — But KUDOS for using the search (as that’s the only way this would have shown up)

    2) The code snippet is hard to read, if you can repost it, using [code][/code] tags around it, it’ll preserve the indents, making it easier to read.

    3) Oddly enough, your problem is the same as the original thread… you’ve got an IF statement that is never closed off… EVERYTIME you have an if, you should have an END IF to go with it.

    -tg


  7. Aug 19th, 2009, 02:51 PM


    #7

    anoble1 is offline


    New Member


    Re: Compile Error: Next without For


  8. Mar 2nd, 2012, 11:19 AM


    #8

    Hijazzer is offline


    New Member


    Re: Compile Error: Next without For

    im having same error but why ?

    Code:

    Dim Ge�ici(28),Kalıcı(28) as integer
    Public Sub RandomIndis()
    Dim i, k As Integer
    Ge�ici(0) = RandomSayi(0, 80)
    Kalıcı(0) = Ge�ici(0)
    i = 1
    While (i < 28)
    Ge�ici(i) = RandomSayi(0, 80)
    
        For k = 0 To i - 1 
           If (Ge�ici(i) <> Ge�ici(k)) Then
        Next k
            Kalıcı(i) = Ge�ici(i)
            i = i + 1
           End If
    enddo
    
    End Sub


  9. Mar 2nd, 2012, 11:22 AM


    #9

    Hijazzer is offline


    New Member


    Re: Compile Error: Next without For

    Quote Originally Posted by Hijazzer
    View Post

    im having same error but why ?

    Code:

    Dim Ge�ici(28),Kalıcı(28) as integer
    Public Sub RandomIndis()
    Dim i, k As Integer
    Ge�ici(0) = RandomSayi(0, 80)
    Kalıcı(0) = Ge�ici(0)
    i = 1
    While (i < 28)
    Ge�ici(i) = RandomSayi(0, 80)
    
        For k = 0 To i - 1 
           If (Ge�ici(i) <> Ge�ici(k)) Then
        Next k
            Kalıcı(i) = Ge�ici(i)
            i = i + 1
           End If
    Wend
    
    End Sub

    hehe tried a couple of loop combinations thats why i missed that enddo statement


  10. Mar 2nd, 2012, 11:23 AM


    #10

    Re: Compile Error: Next without For

    Either your ‘Next k’ or ‘End If’ are in the wrong place


  11. Mar 2nd, 2012, 11:47 AM


    #11

    Hijazzer is offline


    New Member


    Re: Compile Error: Next without For

    im trying to pick not duplicated 29 random number in range 0-80. For this i define a function to pick a random number in definable range.

    Code:

    Function RandomSayi(ByVal enküçük As Integer, ByVal enbüyük As Integer) As Integer
    RandomSayi = Int((enbüyük - enküçük + 1) * Rnd + enküçük)
    End Function

    after that i define global 2 arrays which range is 29 named Geçici(28) and Kalıcı(28)

    Code:

    Dim Kalıcı(28), Geçici(28) as integer

    and than i wanted a public Sub for Creating a Kalıcı(28) array whose members are random and not duplicated integers

    Code:

    Public Sub RandomIndis()
    Dim i, k As Integer
    Geçici(0) = RandomSayi(0, 80)
    Kalıcı(0) = Geçici(0)
    i = 1
    While (i < 28)
    Geçici(i) = RandomSayi(0, 80)
    
        For k = 0 To i - 1 Step 1
           If (Geçici(i) <> Geçici(k)) Then
        Next k
         Kalıcı(i) = Geçici(i)
            lbIndis.AddItem (Str(Kalıcı(i)))
           i = i + 1
        End If
       
    Wend

    in this algorythm i want to pick the Geçici(i) and check ifnot there is any duplicated members in same array . and if it cant find any duplicates it will be my Kalıcı(i) array’s i. member ; To do this i need to put
    next k code
    the exact place that already it placed..


  12. Mar 2nd, 2012, 12:14 PM


    #12

    Hijazzer is offline


    New Member


    Re: Compile Error: Next without For

    i changed my algorythm with a boolean type controller but still it adds some dublicated numbers.

    Code:

    Public Sub RandomIndis()
    Dim i, k As Integer
    Dim kontrol As Boolean
    Geçici(0) = RandomSayi(0, 80)
    Kalıcı(0) = Geçici(0)
    i = 1
    kontrol = True
    While (i < 28)
    Geçici(i) = RandomSayi(0, 80)
    
        For k = 0 To i - 1 Step 1
           If (Geçici(i) = Geçici(k)) Then
         kontrol = False
         Else
         kontrol = True
         End If
         Next k
         If (kontrol = True) Then
         Kalıcı(i) = Geçici(i)
            lbIndis.AddItem (Str(Kalıcı(i)))
           i = i + 1
           Else
          i = i - 1
        End If
       
    Wend
    lbIndis.AddItem (Str(i))
    
    End Sub


  13. Mar 2nd, 2012, 12:43 PM


    #13

    Re: Compile Error: Next without For

    close… after setting your boolean when you find the duplicate, you need to exit the for loop… otherwise when it checks the next number, it DOESN’T match and it re-sets your boolean.

    The alternative is to set the boolean to FALSE before you start you loop AND ONLY change it when you find a match.

    or both… which is probably how I’d do it given the code you have.

    Code:

    Dim FoundDuplicate as boolean
    While (i < 28)
    Geçici(i) = RandomSayi(0, 80)
      FoundDuplicate = False 'assume no duplicate
        For k = 0 To i - 1 Step 1
           If (Geçici(i) = Geçici(k)) Then
             FoundDuplicate = True ' set a flag showing we found a duplicate
             exit For ' this exits the for loop... since we found a duplicate, there's no point in checking the rest.
           End If
         Next k
         If not FoundDuplicate  Then 'if no duplicate was found
            Kalıcı(i) = Geçici(i)
            lbIndis.AddItem (Str(Kalıcı(i)))
            i = i + 1 ' move on to the next one
        End If
       
    Wend

    -tg


  14. Mar 2nd, 2012, 12:59 PM


    #14

    Hijazzer is offline


    New Member


    Re: Compile Error: Next without For


  15. Mar 2nd, 2012, 05:49 PM


    #15

    incidentals is offline


    Frenzied Member


    Re: Compile Error: Next without For

    Am I correct in thinking you want 29 random numbers from the range 0-80?

    her to suggest another easier way to do this, if this is what you are doing.


  16. Mar 2nd, 2012, 07:35 PM


    #16

    Hijazzer is offline


    New Member


    Re: Compile Error: Next without For

    Nope i want 29 numbers between 0-80 range without any duplicates.


  • Home
  • VBForums
  • Visual Basic
  • Office Development
  • Compile Error: Next without For


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules


Click Here to Expand Forum to Full Width

  • #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

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.

DanteAmor

  1. 09-29-2021, 11:13 AM


    #1

    knykil is offline


    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).Activate

    If Range(«D14») = «» Then

    Next i
    End If

    Range(«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)).Select

    Next i

    End With

    Worksheets(«Instructions»).Activate

    Application.ScreenUpdating = True

    End Sub

    Last edited by knykil; 09-29-2021 at 12:03 PM.


  2. 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!!!


  3. 09-29-2021, 11:55 AM


    #3

    Re: Compile Error: Next without For


  4. 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


  5. 09-29-2021, 12:05 PM


    #5

    knykil is offline


    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.


  6. 09-29-2021, 12:37 PM


    #6

    Re: Compile Error: Next without For

    Surely sales stage should be skipped as well


  7. 09-29-2021, 01:12 PM


    #7

    knykil is offline


    Registered User


    Re: Compile Error: Next without For

    Quote Originally Posted by sintek
    View Post

    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?


  8. 09-29-2021, 01:55 PM


    #8

    knykil is offline


    Registered User


    Re: Compile Error: Next without For

    Quote Originally Posted by TMS
    View Post

    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?


  9. 09-29-2021, 01:56 PM


    #9

    knykil is offline


    Registered User


    Re: Compile Error: Next without For

    Quote Originally Posted by rorya
    View Post

    Rorya — I’ve since added an excel example. I’m new to VBA, could you spell it out for me?


  10. 09-29-2021, 03:11 PM


    #10

    Re: Compile Error: Next without For

    So then back to initial solution provided skipping «J MFI» tab


  11. 09-30-2021, 07:39 AM


    #11

    knykil is offline


    Registered User


    Re: Compile Error: Next without For

    Quote Originally Posted by sintek
    View Post

    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?


  12. 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.


  13. 09-30-2021, 07:56 AM


    #13

    Re: Compile Error: Next without For


  14. 09-30-2021, 08:06 AM


    #14

    knykil is offline


    Registered User


    Re: Compile Error: Next without For

    Rorya — spot on! Thank you so much for your help! Cheers!


  15. 09-30-2021, 08:08 AM


    #15

    knykil is offline


    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.


  16. 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…


  17. 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’.


  18. 09-30-2021, 09:04 AM


    #18

    Re: Compile Error: Next without For


Понравилась статья? Поделить с друзьями:
  • Compile error method or data member not found vba
  • Compile error macro excel
  • Compile error invalid use of property
  • Compile error invalid outside procedure excel
  • Compile error invalid or unqualified reference vba