Меню

Vba excel ошибка next without for

This error occurs when the condition is not closed.
You must don’t forger close if conditions.

for example:

Public Sub start_r()

    LastRow = SPT_DB.Range("D" & Rows.count).End(xlUp).Row

Dim i As Long
For i = 3 To 132

    State = Cells(1, i)

    Dim j As Long
    For j = 2 To LastRow

        m = SPT_DB.Cells(j, 4).Value
        z = SPT_DB.Cells(j, 5).Value
        n1 = SPT_DB.Cells(j, 6).Value
        fc = SPT_DB.Cells(j, 7).Value
        am = SPT_DB.Cells(j, 8).Value
        sp = SPT_DB.Cells(j, 10).Value
        sr = SPT_DB.Cells(j, 11).Value
        liq = SPT_DB.Cells(j, 13).Value

        num1 = Val(Left(State, 1))
        num2 = Val(Mid(State, 3, 1))
        num3 = Val(Mid(State, 5, 1))
        num4 = Val(Mid(State, 7, 1))
        num5 = Val(Mid(State, 9, 1))

        Dim spt_class As spt_class
        Set spt_class = New spt_class

        Select Case num1
            Case Is = 1: Call spt_class.rd_r1
            Case Is = 2: Call spt_class.rd_r2
            Case Is = 3: Call spt_class.rd_r3
            Case Is = 4: Call spt_class.rd_r4
        End Select

        Select Case num2
            Case Is = 1: Call spt_class.msf_r1
            Case Is = 2: Call spt_class.msf_r2
            Case Is = 3: Call spt_class.msf_r3
            Case Is = 4: Call spt_class.msf_r4
            Case Is = 5: Call spt_class.msf_r5
            Case Is = 6: Call spt_class.msf_r6
        End Select

        Select Case num3
            Case Is = 0:
            Case Is = 1: Call spt_class.n1_cs_r1
            Case Is = 2: Call spt_class.n1_cs_r2
            Case Is = 3: Call spt_class.n1_cs_r3
        End Select

        Select Case num4
            Case Is = 0:
            Case Is = 1: Call spt_class.dr_r1
            Case Is = 2: Call spt_class.dr_r2
            Case Is = 3: Call spt_class.dr_r3
            Case Is = 4: Call spt_class.dr_r4
        End Select

        Select Case num5
            Case Is = 1: Call spt_class.crr_r1
            Case Is = 2: Call spt_class.crr_r2
            Case Is = 3: Call spt_class.crr_r3
            Case Is = 4: Call spt_class.crr_r4
            Case Is = 5: Call spt_class.crr_r5
            Case Is = 6: Call spt_class.crr_r6
            Case Is = 7: Call spt_class.crr_r7
            Case Is = 8: Call spt_class.crr_r8
            Case Is = 9: Call spt_class.crr_r9
        End Select

        Call spt_class.lvr_r

    Next j


        If cnt_f_1_all = 0 Then
            Cells(4, i) = 0
        Else
            Cells(4, i) = cnt_f_1_liq * 100 / cnt_f_1_all
            Cells(4, i).NumberFormat = "#,##0.00"
        End If
        If cnt_f_2_all = 0 Then
            Cells(5, i) = 0
        Else
            Cells(5, i) = cnt_f_2_liq * 100 / cnt_f_2_all
            Cells(5, i).NumberFormat = "#,##0.00"
        End If
        If cnt_f_3_all = 0 Then
            Cells(6, i) = 0
        Else
            Cells(6, i) = cnt_f_3_liq * 100 / cnt_f_3_all
            Cells(6, i).NumberFormat = "#,##0.00"
        End If
        If cnt_f_4_all = 0 Then
            Cells(7, i) = 0
        Else
            Cells(7, i) = cnt_f_4_liq * 100 / cnt_f_4_all
            Cells(7, i).NumberFormat = "#,##0.00"
        End If


        If cnt_f_n0_1_all = 0 Then
            Cells(14, i) = 0
        Else
            Cells(14, i) = cnt_f_n0_1_liq * 100 / cnt_f_n0_1_all
            Cells(14, i).NumberFormat = "#,##0.00"
        End If
        If cnt_f_n0_2_all = 0 Then
            Cells(15, i) = 0
        Else
            Cells(15, i) = cnt_f_n0_2_liq * 100 / cnt_f_n0_2_all
            Cells(15, i).NumberFormat = "#,##0.00"
        End If
        If cnt_f_n0_3_all = 0 Then
            Cells(16, i) = 0
        Else
            Cells(16, i) = cnt_f_n0_3_liq * 100 / cnt_f_n0_3_all
            Cells(16, i).NumberFormat = "#,##0.00"
        End If
        If cnt_f_n0_4_all = 0 Then
            Cells(17, i) = 0
        Else
            Cells(17, i) = cnt_f_n0_4_liq * 100 / cnt_f_n0_4_all
            Cells(17, i).NumberFormat = "#,##0.00"
        End If


        If cnt_f_n1_1_all = 0 Then
            Cells(24, i) = 0
        Else
            Cells(24, i) = cnt_f_n1_1_liq * 100 / cnt_f_n1_1_all
            Cells(24, i).NumberFormat = "#,##0.00"
        End If
        If cnt_f_n1_2_all = 0 Then
            Cells(25, i) = 0
        Else
            Cells(25, i) = cnt_f_n1_2_liq * 100 / cnt_f_n1_2_all
            Cells(25, i).NumberFormat = "#,##0.00"
        End If
        If cnt_f_n1_3_all = 0 Then
            Cells(26, i) = 0
        Else
            Cells(26, i) = cnt_f_n1_3_liq * 100 / cnt_f_n1_3_all
            Cells(26, i).NumberFormat = "#,##0.00"
        End If
        If cnt_f_n1_4_all = 0 Then
            Cells(27, i) = 0
        Else
            Cells(27, i) = cnt_f_n1_4_liq * 100 / cnt_f_n1_4_all
            Cells(27, i).NumberFormat = "#,##0.00"
        End If


        If cnt_f_n2_1_all = 0 Then
            Cells(34, i) = 0
        Else
            Cells(34, i) = cnt_f_n2_1_liq * 100 / cnt_f_n2_1_all
            Cells(34, i).NumberFormat = "#,##0.00"
        End If
        If cnt_f_n2_2_all = 0 Then
            Cells(35, i) = 0
        Else
            Cells(35, i) = cnt_f_n2_2_liq * 100 / cnt_f_n2_2_all
            Cells(35, i).NumberFormat = "#,##0.00"
        End If
        If cnt_f_n2_3_all = 0 Then
            Cells(36, i) = 0
        Else
            Cells(36, i) = cnt_f_n2_3_liq * 100 / cnt_f_n2_3_all
            Cells(36, i).NumberFormat = "#,##0.00"
        End If
        If cnt_f_n2_4_all = 0 Then
            Cells(37, i) = 0
        Else
            Cells(37, i) = cnt_f_n2_4_liq * 100 / cnt_f_n2_4_all
            Cells(37, i).NumberFormat = "#,##0.00"
        End If


        If cnt_f_n3_1_all = 0 Then
            Cells(44, i) = 0
        Else
            Cells(44, i) = cnt_f_n3_1_liq * 100 / cnt_f_n3_1_all
            Cells(44, i).NumberFormat = "#,##0.00"
        End If
        If cnt_f_n3_2_all = 0 Then
            Cells(45, i) = 0
        Else
            Cells(45, i) = cnt_f_n3_2_liq * 100 / cnt_f_n3_2_all
            Cells(45, i).NumberFormat = "#,##0.00"
        End If
        If cnt_f_n3_3_all = 0 Then
            Cells(46, i) = 0
        Else
            Cells(46, i) = cnt_f_n3_3_liq * 100 / cnt_f_n3_3_all
            Cells(46, i).NumberFormat = "#,##0.00"
        End If
        If cnt_f_n3_4_all = 0 Then
            Cells(47, i) = 0
        Else
            Cells(47, i) = cnt_f_n3_4_liq * 100 / cnt_f_n3_4_all
            Cells(47, i).NumberFormat = "#,##0.00"
        End If

Next i

        cnt_f_1_liq = 0
        cnt_f_2_liq = 0
        cnt_f_3_liq = 0
        cnt_f_4_liq = 0
        cnt_f_1_all = 0
        cnt_f_2_all = 0
        cnt_f_3_all = 0
        cnt_f_4_all = 0

        cnt_f_n0_1_liq = 0
        cnt_f_n0_2_liq = 0
        cnt_f_n0_3_liq = 0
        cnt_f_n0_4_liq = 0
        cnt_f_n0_1_all = 0
        cnt_f_n0_2_all = 0
        cnt_f_n0_3_all = 0
        cnt_f_n0_4_all = 0

        cnt_f_n1_1_liq = 0
        cnt_f_n1_2_liq = 0
        cnt_f_n1_3_liq = 0
        cnt_f_n1_4_liq = 0
        cnt_f_n1_1_all = 0
        cnt_f_n1_2_all = 0
        cnt_f_n1_3_all = 0
        cnt_f_n1_4_all = 0

        cnt_f_n2_1_liq = 0
        cnt_f_n2_2_liq = 0
        cnt_f_n2_3_liq = 0
        cnt_f_n2_4_liq = 0
        cnt_f_n2_1_all = 0
        cnt_f_n2_2_all = 0
        cnt_f_n2_3_all = 0
        cnt_f_n2_4_all = 0

        cnt_f_n3_1_liq = 0
        cnt_f_n3_2_liq = 0
        cnt_f_n3_3_liq = 0
        cnt_f_n3_4_liq = 0
        cnt_f_n3_1_all = 0
        cnt_f_n3_2_all = 0
        cnt_f_n3_3_all = 0
        cnt_f_n3_4_all = 0

End Sub

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]

Макрос останавливается с ошибкой Next без For

Lebron300

Дата: Четверг, 18.12.2014, 20:05 |
Сообщение № 1

Группа: Пользователи

Ранг: Новичок

Сообщений: 19


Репутация:

0

±

Замечаний:
40% ±


Excel 2003

Нужно сделать вывод типа сахарного диабета — 1 или 2 (1 тип — <=3; 2 тип — >3). Выскакивает ошибка на Next R.
[vba]

Код

Private Sub CommandButton2_Click()
      Dim NORM As Range, R, T
      Set NORM = Range(«НОРМА»)
      For R = 1 To 7
          Debug.Print Controls(«TextBox» & R).Text
          T = CDbl(Replace(Controls(«TextBox» & R).Text, «.», «,»))

          If T < NORM(R, 2) Or T > NORM(R, 3) Then
              If Val(TextBox2.Text) < 8 Then
                  st = «Легкая степень тяжести»
              ElseIf Val(TextBox2.Text) > 14 Then
                  st = «Тяжелый случай»
              Else
                  st = «Средняя степень тяжести»
              End If
              If T < NORM(R, 2) Or T > NORM(R, 3) Then
              If Val(TextBox5.Text) <= 3 Then
                  st = «1 типа»
              ElseIf Val(TextBox5.Text) > 3 Then
                  st = «2 типа»
              End If
              MsgBox «Пациент болен. Сахарный диабет!» & vbLf & st, 64, NORM(R, 1)
              Exit Sub
          End If
      Next R
      MsgBox «Пациент здоров!», 64, «»
End Sub

[/vba]

К сообщению приложен файл: VBA.xls(78.5 Kb)

 

Ответить

Pelena

Дата: Четверг, 18.12.2014, 20:14 |
Сообщение № 2

Группа: Админы

Ранг: Местный житель

Сообщений: 18693


Репутация:

4250

±

Замечаний:
±


Excel 2016 & Mac Excel

У Вас первый If не закрыт End If


«Черт возьми, Холмс! Но как??!!»
Ю-money 41001765434816

 

Ответить

Lebron300

Дата: Четверг, 18.12.2014, 20:16 |
Сообщение № 3

Группа: Пользователи

Ранг: Новичок

Сообщений: 19


Репутация:

0

±

Замечаний:
40% ±


Excel 2003

Pelena, закрыт же[vba]

Код

st = «Средняя степень тяжести»
             End If

[/vba]

 

Ответить

Pelena

Дата: Четверг, 18.12.2014, 20:18 |
Сообщение № 4

Группа: Админы

Ранг: Местный житель

Сообщений: 18693


Репутация:

4250

±

Замечаний:
±


Excel 2016 & Mac Excel

Это внутренний If, вот после него добавьте ещё один End If
[vba]

Код

    st = «Средняя степень тяжести»
End If
End If

[/vba]


«Черт возьми, Холмс! Но как??!!»
Ю-money 41001765434816

 

Ответить

Lebron300

Дата: Четверг, 18.12.2014, 20:26 |
Сообщение № 5

Группа: Пользователи

Ранг: Новичок

Сообщений: 19


Репутация:

0

±

Замечаний:
40% ±


Excel 2003

Pelena, да точно… но теперь он мне только тип выводит, как сделать чтобы и степень тяжести тоже выводил

 

Ответить

Pelena

Дата: Четверг, 18.12.2014, 20:34 |
Сообщение № 6

Группа: Админы

Ранг: Местный житель

Сообщений: 18693


Репутация:

4250

±

Замечаний:
±


Excel 2016 & Mac Excel

А для степени тяжести у Вас и не предусмотрен вывод. В каком виде это должно выводится?


«Черт возьми, Холмс! Но как??!!»
Ю-money 41001765434816

 

Ответить

Lebron300

Дата: Четверг, 18.12.2014, 20:38 |
Сообщение № 7

Группа: Пользователи

Ранг: Новичок

Сообщений: 19


Репутация:

0

±

Замечаний:
40% ±


Excel 2003

Pelena, Пациент болен. Сахарный диабет Средняя степень тяжести 1 типа… все в одном окошке

 

Ответить

Pelena

Дата: Четверг, 18.12.2014, 20:41 |
Сообщение № 8

Группа: Админы

Ранг: Местный житель

Сообщений: 18693


Репутация:

4250

±

Замечаний:
±


Excel 2016 & Mac Excel

[vba]

Код

  If Val(TextBox5.Text) <= 3 Then
    st = st & » » & «1 типа»
      ElseIf Val(TextBox5.Text) > 3 Then
    st = st & » » & «2 типа»
End If

[/vba]


«Черт возьми, Холмс! Но как??!!»
Ю-money 41001765434816

 

Ответить

Lebron300

Дата: Четверг, 18.12.2014, 20:45 |
Сообщение № 9

Группа: Пользователи

Ранг: Новичок

Сообщений: 19


Репутация:

0

±

Замечаний:
40% ±


Excel 2003

Pelena, огромное спасибо))

 

Ответить

Rezeda R

0 / 0 / 1

Регистрация: 23.05.2013

Сообщений: 16

1

15.11.2014, 18:01. Показов 6527. Ответов 2

Метки нет (Все метки)


Подскажите пож. почему первый Next выдает ошибку Next Without For .
Пробовала поменять местами next i endif не помогло.

Visual Basic
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
Sub zad7()
k = Selection.Columns.Count
Dim x() As Variant
ReDim x(k)
Dim y() As Variant
ReDim y(k)
Dim z() As Variant
ReDim z(k)
m = Cells(5, 1)
n = Cells(5, 2)
 
s = 0
proiz = 0
For i = 1 To k
x(i) = Selection.Cells(1, i)
y(i) = Selection.Cells(2, i)
proiz = proiz + (x(i)) ^ 2
Next
 
For i = 1 To k
x(i) = Selection.Cells(1, i)
y(i) = Selection.Cells(2, i)
If x(i) + y(i) > m Or n < proiz Then
z(i) = (x(i) - y(i)) ^ 2
Else
If (x(i) + y(i)) > m And Abs(x(i)) > 2 Then
z(i) = (x(i) + y(i)) / m
Else: z(i) = (m * x(i))
End If
Next
For i = 1 To k
s = (z(i) + y(i)) / (x(i)) ^ 3
Next
t = m * ((Abs(s)) ^ 1 / 3)
Cells(2, 12) = t
 
End Sub

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



SoftIce

es geht mir gut

11264 / 4746 / 1183

Регистрация: 27.07.2011

Сообщений: 11,437

15.11.2014, 19:48

2

Попробуйте объединить 25 и 26 строки.

Visual Basic
1
ElseIf (x(i) + y(i)) > m And Abs(x(i)) > 2 Then



0



Antonio_Goodwin

84 / 11 / 7

Регистрация: 08.09.2013

Сообщений: 41

16.11.2014, 21:21

3

После строки 29 должен стоять еще один End If
как-то так:

Visual Basic
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
Sub zad7()
k = Selection.Columns.Count
Dim x() As Variant
ReDim x(k)
Dim y() As Variant
ReDim y(k)
Dim z() As Variant
ReDim z(k)
m = Cells(5, 1)
n = Cells(5, 2)
 
s = 0
proiz = 0
For i = 1 To k
x(i) = Selection.Cells(1, i)
y(i) = Selection.Cells(2, i)
proiz = proiz + (x(i)) ^ 2
Next
 
For i = 1 To k
    x(i) = Selection.Cells(1, i)
    y(i) = Selection.Cells(2, i)
    If x(i) + y(i) > m Or n < proiz Then
        z(i) = (x(i) - y(i)) ^ 2
    Else
        If (x(i) + y(i)) > m And Abs(x(i)) > 2 Then
            z(i) = (x(i) + y(i)) / m
        Else
            z(i) = (m * x(i))
        End If
    End If
Next
For i = 1 To k
s = (z(i) + y(i)) / (x(i)) ^ 3
Next i
t = m * ((Abs(s)) ^ 1 / 3)
Cells(2, 12) = t
End Sub



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

16.11.2014, 21:21

Помогаю со студенческими работами здесь

Выводит ошибку
В строчке IntToStr(Edit1.Text, a ,c); выводит ошибку в a и c. Что делать?

procedure…

выводит ошибку
в 82 строке

#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;iostream&gt;
#include &lt;ctime&gt;

Выводит ошибку
В чем проблема, никак не могу понять
#include&lt;iostream&gt;
int main()
{
int year;…

Выводит ошибку переполнение
Если в строке находится выражение t+x^2+1, то выдает ошибку EOleException with message…

Выводит ошибку в структуре
Создать структуру &quot;мобильный телефон&quot;, состоящую из полей — &quot;Номер абонента&quot;(строка из 7 цифр),…

компилятор выводит ошибку
Тут пользователь вводит любое 6-ти значное число и нужно и нужно определить счастливое оно или нет….

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

3

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

‘————————————————-

Round to nearest half hour?

Use =MROUND(A2,»0:30″) to round to nearest half hour. Use =CEILING(A2,»0:30″) to round to next half hour.

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

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Vaillant turbo max ошибки
  • Vba excel ошибка 457