Ошибка loop do как исправить

Ilin Andrian

0 / 0 / 0

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

Сообщений: 65

1

05.03.2022, 16:09. Показов 868. Ответов 7

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


Студворк — интернет-сервис помощи студентам

Когда я писал код для файла с расширением vbs — мне выдаёт такую ошибку, что делать?

Сценарий: CUsersUserDesktopvbs.vbs
Строка: 13
Символ: 1
Ошибка ‘loop’ вне ‘do’
Код: 800A040E
Источник: Ошибка компиляции Microsoft VBScript

Код:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
Do
msgbox"Это vbs файл",48,"vbs"
x = inputbox("Введите команду, если вы не знаете команд. То введите Список команд")
if (x = "Открой гугл") then
createobject("Wscript.Shell").run "cmd /c C:UsersUserDesktoptesttest1.bat", 0
if (x = "Список команд") then
createobject("Wscript.Shell").run "cmd /c C:UsersUserDesktoptestvbs.txt", 0
 
exit do
else
msgbox"Такой команды нету",48,"Ошибочка"
end if
loop



0



Programming

Эксперт

94731 / 64177 / 26122

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

Сообщений: 116,782

05.03.2022, 16:09

Ответы с готовыми решениями:

Ошибка: Индекс находился вне границ массива. В чём проблема?
Пишет ошибку в процедуре "zamena’.
Uses Crt;
Type matr=array of integer;
Var A,B,C:matr;

Проблема с функцией loop
(loop
for item in list
for i from 1 to 10
do (something))

EVFUN: Не найдена функция LOOPFOR…

проблема с командой loop
mov ebx,offset mas1
xor eax,eax
mov ecx,5
cikl1:
.if eax<
mov eax, …

Open Loop и Closed Loop системы, какие утверждения верны?
1) В системах Open Loop можно обойтись без измерения фактического значения.
2) В случае большой…

Найти среднее арифметическое отрицательных чисел, введенных с клавиатуры, используя do-loop while/do-loop until
Нужна помощь. Найти среднее арифметическое отрицательных чисел, введенных с клавиатуры, используя…

7

2927 / 1758 / 206

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

Сообщений: 6,539

Записей в блоге: 6

05.03.2022, 17:09

2

Цитата
Сообщение от Ilin Andrian
Посмотреть сообщение

мне выдаёт такую ошибку

Цитата
Сообщение от Ilin Andrian
Посмотреть сообщение

Ошибка ‘loop’ вне ‘do’

И что из этого непонятно?

Цитата
Сообщение от Ilin Andrian
Посмотреть сообщение

что делать?

Посчитайте число if и завершающих их end if.



0



0 / 0 / 0

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

Сообщений: 65

05.03.2022, 17:16

 [ТС]

3

Ничего не понял можно по подробней. Я просто ещё ничего не понимаю.



0



I can

Нарушитель

3700 / 3232 / 707

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

Сообщений: 7,534

05.03.2022, 17:28

4

Visual Basic
1
2
3
4
5
6
7
Do
msgbox "Это vbs файл",48,"vbs"
x = inputbox("Введите команду, если вы не знаете команд. То введите Список команд")
if (x = "Открой гугл") then createobject("Wscript.Shell").run "cmd /c C:UsersUserDesktoptesttest1.bat", 0:exit do
if (x = "Список команд") then createobject("Wscript.Shell").run "cmd /c C:UsersUserDesktoptestvbs.txt", 0:exit do
msgbox"Такой команды нету",48,"Ошибочка"
loop



1



Ilin Andrian

0 / 0 / 0

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

Сообщений: 65

05.03.2022, 17:32

 [ТС]

5

Пишу ещё раз. Что мне делать если выдаёт такую ошибку —

Сценарий: CUsersUserDesktopvbs.vbs
Строка: 13
Символ: 1
Ошибка ‘loop’ вне ‘do’
Код: 800A040E
Источник: Ошибка компиляции Microsoft VBScript

Код:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
Do
msgbox"Это vbs файл",48,"vbs"
x = inputbox("Введите команду, если вы не знаете команд. То введите Список команд")
if (x = "Открой гугл") then
createobject("Wscript.Shell").run "cmd /c C:UsersUserDesktoptesttest1.bat", 0
if (x = "Список команд") then
createobject("Wscript.Shell").run "cmd /c C:UsersUserDesktoptestvbs.txt", 0
 
exit do
else
msgbox"Такой команды нету",48,"Ошибочка"
end if
loop

Ну а если убрать —

Visual Basic
1
2
if (x = "Список команд") then
createobject("Wscript.Shell").run "cmd /c C:UsersUserDesktoptestvbs.txt", 0

То ошибка пропадает, но мне нужно сделать так что бы можно было вписать несколько текстов и открывались bat и текстовые файлы. Помогите пожалуйста!!



0



Нарушитель

3700 / 3232 / 707

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

Сообщений: 7,534

05.03.2022, 19:01

6

Цитата
Сообщение от Ilin Andrian
Посмотреть сообщение

То ошибка пропадает, но мне нужно сделать так что бы можно было вписать несколько текстов и открывались bat и текстовые файлы. Помогите пожалуйста!!

Я же дал код полностью. В чём проблема?

Добавлено через 6 минут

Цитата
Сообщение от Ilin Andrian
Посмотреть сообщение

Что мне делать если выдаёт такую ошибку —

End If ‘ написать между пятой и шестой строкой, или использовать мой пример.



0



2927 / 1758 / 206

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

Сообщений: 6,539

Записей в блоге: 6

05.03.2022, 19:59

7

Цитата
Сообщение от Ilin Andrian
Посмотреть сообщение

Ничего не понял можно по подробней.

Вы считать не умеете?
1+1-1 не равно 0, а должно быть равно 0. Вот сделайте так чтобы количество if было равно количеству end if.
Изучите язык на котором пишите, иначе ничего нормально не получится.



2



Нарушитель

3700 / 3232 / 707

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

Сообщений: 7,534

05.03.2022, 20:01

8

Цитата
Сообщение от locm
Посмотреть сообщение

Вы считать не умеете?

Он не считатель



2



IT_Exp

Эксперт

87844 / 49110 / 22898

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

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

05.03.2022, 20:01

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

Как создать 4 варианта программы c For/Next,Do While / Loop, Do Loop /Until , If Then Goto
Создать 4 варианта программы c,m For/Next,Do While / Loop, Do Loop /Until , If Then Goto…

Нужно написать программу с циклом Do While.Loop или Do.Loop Until
Составить алгоритм и написать программу нахождения для введенных 15 чисел сумму, если число…

Как проверить подключен ли javascript или у меня другая ошибка,у меня на сайте этот код не работает
<p>
<select name="id_mon" id="select_mon">
<?php

$result =…

В чём у меня ошибка? Поправьте меня
Приветствую вас! Пишу небольшой движок и тут проблема в конфиге.
Вот код config.php

<?…

Warining For-loop variable ‘i’ may be undefined after loop
Что не так с кодом? При компиляции программы появляется предупреждение:" Unit1.pas(46):For-loop…

Warining For-loop variable ‘i’ may be undefined after loop
Как исправить код, что бы программа работала корректно.

var
Form1: TForm1;

implementation…

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

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

8

Доброго времени суток.  

  Задумка такова:  

  1. Установить счётчик строк на 38.  
2. Если ячейка в столбце А (строка — по счётчику) не пустая, выполнить п.3-5. Если пустая, остановить программу.  
3. Если ячейка в определённом столбце той же строки имеет значение «Оплачено», изменить цвет шрифта в ячейке столбца А той же строки. Если нет, перейти к п.4.  
4. Увеличить счётчик строк на единицу.  
5. Перейти к п.2  

  Код:  

  Sub Hilight ()  
Dim taskcell as Integer  
taskcell = 38  
Do Until Range(«A» & taskcell).Value = «»  
If Range(«A» & taskcell).Offset(0, 2 + User) = («Оплачено») Then  
   Range(«A» & taskcell).Font.ColorIndex = 16  
   Else  
   taskcell = taskcell + 1  
Loop  
End Sub  

  При запуске выдаётся сообщение «Compile error: Loop without Do». Помогите понять ошибку.

Выдает ошибку «Loop without Do» хотя Do есть

Bamboo

Дата: Понедельник, 28.03.2016, 21:50 |
Сообщение № 1

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

Ранг: Участник

Сообщений: 99


Репутация:

0

±

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


Excel 2010

Странная ситуация, цикл исправно работал. А Потом появилась эта ошибка. Хотя Do есть.
Прошу не ругаться на код, это мой первый на VBA да еще и не отлаженный.
[vba]

Код

Function HighLevACC(ACC, DistMap)
Dim Array_DistMap()
Dim Array_SubHLACC()
Dim I As Integer, J As Integer, X As Integer, Y As Integer
Do
X = X + 1
If ACC.Cells(X, 1) = «Empty» And ThisCell.Address.Offset(X, 10) = «» Then      
Set vHLACC = ACC.Cells(X, -1)
Array_DistMap = DistMap.Value
  Counter_j = 0
For I = 1 To UBound(Array_DistMap)
If Array_DistMap(I, 1) = vHLACC Then
J = J + 1
ReDim Preserve Array_SubHLACC(1 To J)
Array_SubHLACC(J) = Array_DistMap(I, 2)
  MsgBox (Array_SubHLACC(J))
  End If
Next
HighLevACC = Array_SubHLACC(2)
HighLevACC.Offset(0, 9) = 1
ACC.Cells(Õ, 9) = «S»      
If ACC.Cells(Õ — 1, 10) = «C» Then       
vHLACC = ACC.Cells(X — 1, -1)
Counter_j = 0
For I = 1 To UBound(Array_DistMap)
If Array_DistMap(I, 1) = vHLACC Then
J = J + 1
ReDim Preserve Array_SubHLACC(0 To J)
Array_SubHLACC(J) = Array_DistMap(I, 2)
  End If
Next
Y = HighLevACC.Offcet(-1, 9)
Y = Y + 1
If Y <= J Then
HighLevACC = Array_SubHLACC(Y)
HighLevACC.Cells(0, 9) = Y
If Y = J Then
HighLevACC.Cells(0, 10) = «D»
End If
End If
End If
HighLevACC = ACC.Cells(X, 1)
Loop While (X < ACC.Count) Or (ACC.Cells(X, 1) = «Empty» And ThisCell.Address.Offset(X, 10) = «»)
End Function

[/vba]

 

Ответить

al-Ex

Дата: Понедельник, 28.03.2016, 22:00 |
Сообщение № 2

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 190


Репутация:

59

±

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


Excel 2010


если цикл начинается с «For I =1 …» тогда уже внизу — «Next I», исправьте в двух местах.
и конструкции типа: If Then
Else
End If
так мудрёно лучше не делать.
Вряд-ли это будет работать именно так как Вы задумали.

Сообщение отредактировал al-ExПонедельник, 28.03.2016, 22:24

 

Ответить

Невилл

Дата: Понедельник, 28.03.2016, 22:09 |
Сообщение № 3

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

Ранг: Участник

Сообщений: 79


Репутация:

2

±

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


Excel 2007

Одно из If не закрыто.

Кстати, неплохо бы определять переменные и их типы сверху, пожалуй.

 

Ответить

Апострофф

Дата: Понедельник, 28.03.2016, 22:10 |
Сообщение № 4

Группа: Проверенные

Ранг: Обитатель

Сообщений: 431


Репутация:

120

±

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


Excel 1997

Учитесь оформлять код отступами — и проблем не будет
[vba]

Код

Function HighLevACC(ACC, DistMap)
Dim Array_DistMap()
Dim Array_SubHLACC()
Dim I As Integer, J As Integer, X As Integer, Y As Integer
Do
    X = X + 1
    If ACC.Cells(X, 1) = «Empty» And ThisCell.Address.Offset(X, 10) = «» Then
        Set vHLACC = ACC.Cells(X, -1)
        Array_DistMap = DistMap.Value
        Counter_j = 0
        For I = 1 To UBound(Array_DistMap)
            If Array_DistMap(I, 1) = vHLACC Then
                J = J + 1
                ReDim Preserve Array_SubHLACC(1 To J)
                Array_SubHLACC(J) = Array_DistMap(I, 2)
                MsgBox (Array_SubHLACC(J))
            End If
        Next
        HighLevACC = Array_SubHLACC(2)
        HighLevACC.Offset(0, 9) = 1
        ACC.Cells(O, 9) = «S»
        If ACC.Cells(O — 1, 10) = «C» Then
            vHLACC = ACC.Cells(X — 1, -1)
            Counter_j = 0
            For I = 1 To UBound(Array_DistMap)
                If Array_DistMap(I, 1) = vHLACC Then
                    J = J + 1
                    ReDim Preserve Array_SubHLACC(0 To J)
                    Array_SubHLACC(J) = Array_DistMap(I, 2)
                End If
            Next
            Y = HighLevACC.Offcet(-1, 9)
            Y = Y + 1
            If Y <= J Then
                HighLevACC = Array_SubHLACC(Y)
                HighLevACC.Cells(0, 9) = Y
                If Y = J Then
                    HighLevACC.Cells(0, 10) = «D»
                End If
            End If
        End If
    End If ‘НЕ ХВАТАЛО ЭТОГО.
    HighLevACC = ACC.Cells(X, 1)
Loop While (X < ACC.Count) Or (ACC.Cells(X, 1) = «Empty» And ThisCell.Address.Offset(X, 10) = «»)
End Function

[/vba]

Сообщение отредактировал АпостроффПонедельник, 28.03.2016, 22:18

 

Ответить

Bamboo

Дата: Понедельник, 28.03.2016, 22:48 |
Сообщение № 5

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

Ранг: Участник

Сообщений: 99


Репутация:

0

±

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


Excel 2010

Апострофф, Спасибо! Получилось! Насчет, отступов, это я поленился, а зря…

 

Ответить

_Boroda_

Дата: Понедельник, 28.03.2016, 23:02 |
Сообщение № 6

Группа: Модераторы

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

Сообщений: 16620


Репутация:

6465

±

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


2003; 2007; 2010; 2013 RUS

Bamboo, Виталий, я, например, делаю вот так — когда пишу If … Then, то сразу же ДВА раза жму Ентер и пишу End If, затем возвращаюсь на строчку выше, жму Тав и пишу то, что хотел написать внутри Ифа.
Аналогично с циклами — For i = 1 to 5, ДВА раза Ентер, Next i, стрелка вверх, Тав и тело цикла. При таком стиле записи я уже не теряю закрытия циклов и Ifов.
Можно еще пользоваться облегчениями отсюда http://www.excelworld.ru/forum/10-22392-180576-16-1458977793
Кстати, вот это

если цикл начинается с «For I =1 …» тогда уже внизу — «Next I»

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

Насчет, отступов, это я поленился

Отступы легко делать Тавом или в VBA вывести панельку Edit, там есть специальные кнопочки — ими можно делать отступ сразу для нескольких строк (Тавом тоже можно).


Скажи мне, кудесник, любимец ба’гов…
Платная помощь:
Boroda_Excel@mail.ru
Яндекс-деньги: 41001632713405 | Webmoney: R289877159277; Z102172301748; E177867141995

 

Ответить

I’m trying to implement a simple Newton’s method iterative solver using Excel VB (I have never used VB.)

I keep getting the error loop without a Do and I can’t figure out what I’m doing wrong here.

I’m trying to find the roots of the function z^3 - z^2 - (B^2 + B - A)z - A*B called the compressibility factor.

My source MSN

Function zCalculation(ByVal temp As Double, ByVal press As Double) As Double

Dim tempCr As Double
Dim pressCr As Double
Dim A As Double
Dim B As Double

tempCr = temp / 238.5

pressCr = press / 547.424092

A = pressCr / tempCr
A = A / (9 * (2 ^ (1 / 3) - 1))
B = pressCr / tempCr
B = B * (2 ^ (1 / 3) - 1) / 3



Dim zNot As Double
Dim counter As Integer
counter = 0
zNot = 1#

Do
    counter = counter + 1

    zNot = zNot - (zNot ^ 3 - zNot ^ 2 - (B ^ 2 + B - A) * zNot - A * B) / (3 * zNot ^ 2 - 2 * zNot - (B ^ 2 + B - A))
    If counter > 1000 Then
       Exit Do

Loop Until eval(zNot, A, B) < 0.000001


zCalculation = zNot


End Function

break

Function eval(ByVal z As Double, ByVal A As Double, ByVal B As Double) As Double

    eval = z ^ 3 - z ^ 2 - (B ^ 2 + B - A) * z - A * B

End Function

Community's user avatar

asked Dec 9, 2013 at 16:58

Felix Castor's user avatar

Felix CastorFelix Castor

1,5381 gold badge18 silver badges39 bronze badges

You need an:

End If

in your code.

answered Dec 9, 2013 at 17:04

Gary's Student's user avatar

Gary’s StudentGary’s Student

95.4k9 gold badges58 silver badges99 bronze badges

2

You can try:

 Function zCalculation(ByVal temp As Double, ByVal press As Double) As Double

  Dim tempCr As Double
  Dim pressCr As Double
  Dim A As Double
  Dim B As Double

  tempCr = temp / 238.5

  pressCr = press / 0.546789

  A = pressCr / tempCr
  A = A / (9 * (2 ^ (1 / 3) - 1))
  B = pressCr / tempCr
  B = B * (2 ^ (1 / 3) - 1) / 3



  Dim zNot As Double
  Dim counter As Integer
  counter = 0
  zNot = 1#

  Do
      counter = counter + 1

      zNot = zNot - (zNot ^ 3 + zNot ^ 2 - (B ^ 2 + B - A) * zNot - A * B) / (3 * zNot ^ 2 + 2 * zNot - (B ^ 2 + B - A))
      If counter > 1000 Then
         Exit Do
      End if  ' <--- Here

  Loop Until eval(zNot, A, B) < 0.000001

  zCalculation = zNot
 End Function

answered Dec 9, 2013 at 17:06

Makah's user avatar

1

Sub datacalculationsandformat()
Dim row As Integer
row = 2
Do While Cells(row, 2) <> ""
Cells(row, 3).Value = Cells(row, 2).Value * 0.3
Cells(row, 4).Value = Cells(row, 2) * 0.1
Cells(row, 5).Value = Cells(row, 2).Value + Cells(row, 3).Value + Cells(row, 4).Value
If Cells(row, 5).Value >= 8000 Then
Worksheets("Sheet1").Cells(row, 5).Font.Bold = True
row = row + 1
Loop

slavoo's user avatar

slavoo

5,76864 gold badges36 silver badges39 bronze badges

answered Sep 21, 2017 at 5:11

user8646115's user avatar

Выдает ошибку «Loop without Do» хотя Do есть

Bamboo

Дата: Понедельник, 28.03.2016, 21:50 |
Сообщение № 1

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

Ранг: Участник

Сообщений: 99


Репутация:

0

±

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


Excel 2010

Странная ситуация, цикл исправно работал. А Потом появилась эта ошибка. Хотя Do есть.
Прошу не ругаться на код, это мой первый на VBA да еще и не отлаженный.
[vba]

Код

Function HighLevACC(ACC, DistMap)
Dim Array_DistMap()
Dim Array_SubHLACC()
Dim I As Integer, J As Integer, X As Integer, Y As Integer
Do
X = X + 1
If ACC.Cells(X, 1) = «Empty» And ThisCell.Address.Offset(X, 10) = «» Then      
Set vHLACC = ACC.Cells(X, -1)
Array_DistMap = DistMap.Value
  Counter_j = 0
For I = 1 To UBound(Array_DistMap)
If Array_DistMap(I, 1) = vHLACC Then
J = J + 1
ReDim Preserve Array_SubHLACC(1 To J)
Array_SubHLACC(J) = Array_DistMap(I, 2)
  MsgBox (Array_SubHLACC(J))
  End If
Next
HighLevACC = Array_SubHLACC(2)
HighLevACC.Offset(0, 9) = 1
ACC.Cells(Õ, 9) = «S»      
If ACC.Cells(Õ — 1, 10) = «C» Then       
vHLACC = ACC.Cells(X — 1, -1)
Counter_j = 0
For I = 1 To UBound(Array_DistMap)
If Array_DistMap(I, 1) = vHLACC Then
J = J + 1
ReDim Preserve Array_SubHLACC(0 To J)
Array_SubHLACC(J) = Array_DistMap(I, 2)
  End If
Next
Y = HighLevACC.Offcet(-1, 9)
Y = Y + 1
If Y <= J Then
HighLevACC = Array_SubHLACC(Y)
HighLevACC.Cells(0, 9) = Y
If Y = J Then
HighLevACC.Cells(0, 10) = «D»
End If
End If
End If
HighLevACC = ACC.Cells(X, 1)
Loop While (X < ACC.Count) Or (ACC.Cells(X, 1) = «Empty» And ThisCell.Address.Offset(X, 10) = «»)
End Function

[/vba]

 

Ответить

al-Ex

Дата: Понедельник, 28.03.2016, 22:00 |
Сообщение № 2

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 190


Репутация:

59

±

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


Excel 2010


если цикл начинается с «For I =1 …» тогда уже внизу — «Next I», исправьте в двух местах.
и конструкции типа: If Then
Else
End If
так мудрёно лучше не делать.
Вряд-ли это будет работать именно так как Вы задумали.

Сообщение отредактировал al-ExПонедельник, 28.03.2016, 22:24

 

Ответить

Невилл

Дата: Понедельник, 28.03.2016, 22:09 |
Сообщение № 3

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

Ранг: Участник

Сообщений: 79


Репутация:

2

±

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


Excel 2007

Одно из If не закрыто.

Кстати, неплохо бы определять переменные и их типы сверху, пожалуй.

 

Ответить

Апострофф

Дата: Понедельник, 28.03.2016, 22:10 |
Сообщение № 4

Группа: Проверенные

Ранг: Обитатель

Сообщений: 427


Репутация:

120

±

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


Excel 1997

Учитесь оформлять код отступами — и проблем не будет
[vba]

Код

Function HighLevACC(ACC, DistMap)
Dim Array_DistMap()
Dim Array_SubHLACC()
Dim I As Integer, J As Integer, X As Integer, Y As Integer
Do
    X = X + 1
    If ACC.Cells(X, 1) = «Empty» And ThisCell.Address.Offset(X, 10) = «» Then
        Set vHLACC = ACC.Cells(X, -1)
        Array_DistMap = DistMap.Value
        Counter_j = 0
        For I = 1 To UBound(Array_DistMap)
            If Array_DistMap(I, 1) = vHLACC Then
                J = J + 1
                ReDim Preserve Array_SubHLACC(1 To J)
                Array_SubHLACC(J) = Array_DistMap(I, 2)
                MsgBox (Array_SubHLACC(J))
            End If
        Next
        HighLevACC = Array_SubHLACC(2)
        HighLevACC.Offset(0, 9) = 1
        ACC.Cells(O, 9) = «S»
        If ACC.Cells(O — 1, 10) = «C» Then
            vHLACC = ACC.Cells(X — 1, -1)
            Counter_j = 0
            For I = 1 To UBound(Array_DistMap)
                If Array_DistMap(I, 1) = vHLACC Then
                    J = J + 1
                    ReDim Preserve Array_SubHLACC(0 To J)
                    Array_SubHLACC(J) = Array_DistMap(I, 2)
                End If
            Next
            Y = HighLevACC.Offcet(-1, 9)
            Y = Y + 1
            If Y <= J Then
                HighLevACC = Array_SubHLACC(Y)
                HighLevACC.Cells(0, 9) = Y
                If Y = J Then
                    HighLevACC.Cells(0, 10) = «D»
                End If
            End If
        End If
    End If ‘НЕ ХВАТАЛО ЭТОГО.
    HighLevACC = ACC.Cells(X, 1)
Loop While (X < ACC.Count) Or (ACC.Cells(X, 1) = «Empty» And ThisCell.Address.Offset(X, 10) = «»)
End Function

[/vba]

Сообщение отредактировал АпостроффПонедельник, 28.03.2016, 22:18

 

Ответить

Bamboo

Дата: Понедельник, 28.03.2016, 22:48 |
Сообщение № 5

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

Ранг: Участник

Сообщений: 99


Репутация:

0

±

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


Excel 2010

Апострофф, Спасибо! Получилось! Насчет, отступов, это я поленился, а зря…

 

Ответить

_Boroda_

Дата: Понедельник, 28.03.2016, 23:02 |
Сообщение № 6

Группа: Модераторы

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

Сообщений: 16620


Репутация:

6465

±

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


2003; 2007; 2010; 2013 RUS

Bamboo, Виталий, я, например, делаю вот так — когда пишу If … Then, то сразу же ДВА раза жму Ентер и пишу End If, затем возвращаюсь на строчку выше, жму Тав и пишу то, что хотел написать внутри Ифа.
Аналогично с циклами — For i = 1 to 5, ДВА раза Ентер, Next i, стрелка вверх, Тав и тело цикла. При таком стиле записи я уже не теряю закрытия циклов и Ifов.
Можно еще пользоваться облегчениями отсюда http://www.excelworld.ru/forum/10-22392-180576-16-1458977793
Кстати, вот это

если цикл начинается с «For I =1 …» тогда уже внизу — «Next I»

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

Насчет, отступов, это я поленился

Отступы легко делать Тавом или в VBA вывести панельку Edit, там есть специальные кнопочки — ими можно делать отступ сразу для нескольких строк (Тавом тоже можно).


Скажи мне, кудесник, любимец ба’гов…
Платная помощь:
Boroda_Excel@mail.ru
Яндекс-деньги: 41001632713405 | Webmoney: R289877159277; Z102172301748; E177867141995

 

Ответить

Доброго времени суток.  

  Задумка такова:  

  1. Установить счётчик строк на 38.  
2. Если ячейка в столбце А (строка — по счётчику) не пустая, выполнить п.3-5. Если пустая, остановить программу.  
3. Если ячейка в определённом столбце той же строки имеет значение «Оплачено», изменить цвет шрифта в ячейке столбца А той же строки. Если нет, перейти к п.4.  
4. Увеличить счётчик строк на единицу.  
5. Перейти к п.2  

  Код:  

  Sub Hilight ()  
Dim taskcell as Integer  
taskcell = 38  
Do Until Range(«A» & taskcell).Value = «»  
If Range(«A» & taskcell).Offset(0, 2 + User) = («Оплачено») Then  
   Range(«A» & taskcell).Font.ColorIndex = 16  
   Else  
   taskcell = taskcell + 1  
Loop  
End Sub  

  При запуске выдаётся сообщение «Compile error: Loop without Do». Помогите понять ошибку.

Dim r As Long, sr As Long
r = 5
sr = 16


Do While Not IsEmpty(Cells(r, 2).Value)
    
    'Qnty Ignore
    If Cells(r, 3) > 0 Then
    
    'Error Checking: Item Number present?
    If Cells(r, 1).Value < 1 Then
INOINVAL:
    INo = Application.InputBox("ALDI Item No. Missing for " & Cells(r, 2).Value & " Please enter it now", Type:=1)
        
        If INo < 1 Then
        Msgbox ("Incorrect. Must be a 5 digit number")
        GoTo INOINVAL
        End If
    Cells(r, 1).Value = INo
    
    'copying text into SI
    SI.Cells(sr, 1).Value = OI.Cells(r, 1).Value
    SI.Cells(sr, 2).Value = OI.Cells(r, 2).Value
    SI.Cells(sr, 3).Value = OI.Cells(r, 3).Value
    sr = sr + 1
    t = r + 1
    End If
    Loop
  • #1

hi experts….
Can anyone tell me why I get an error message «loop without do»? for this code

Code:

Do While Not rs2.EOF
        For j = LBound(MYarray) To UBound(MYarray)
            If rs2.Fields("ISSUE").Value = MYarray(j) Then
                store = store & "," & rs2.Fields("ENGINEER").Value
            Else
            End If
            rs2.MoveNext
Loop
  • #2

hi experts….
Can anyone tell me why I get an error message «loop without do»? for this code

Code:

Do While Not rs2.EOF
        For j = LBound(MYarray) To UBound(MYarray)
            If rs2.Fields("ISSUE").Value = MYarray(j) Then
                store = store & "," & rs2.Fields("ENGINEER").Value
            Else
            End If
            rs2.MoveNext
Loop

Try using a Next statement instead of MoveNext. Is this all the code? Are you opening a recordset first and then executing these lines? Just asking.

Code:

Do While Not rs2.EOF
        For j = LBound(MYarray) To UBound(MYarray)
            If rs2.Fields("ISSUE").Value = MYarray(j) Then
                store = store & "," & rs2.Fields("ENGINEER").Value
            Else
            End If
        Next
Loop
  • #3

you still need the movenext otherwise rs2 will never reach EOF. And you need the next for the j

Code:

Do While Not rs2.EOF
        For j = LBound(MYarray) To UBound(MYarray)
            If rs2.Fields("ISSUE").Value = MYarray(j) Then
                store = store & "," & rs2.Fields("ENGINEER").Value
            Else
            End If
            rs2.movenext
        Next j
Loop

MajP

MajP

You’ve got your good things, and you’ve got mine.
  • #4

Can anyone tell me why I get an error message «loop without do»? for this code

If you have a broken construct (IF without END IF, Do without Loop, For without Next) and they are nested the error always seems to be the outer nest and not the construct with the actual problem. So the message always seems wrong.
In this case it is broken because you have a FOR without a Next inside the DO Loop. You would expect the error to be FOR WITHOUT NEXT, not LOOP Without DO. Only after seeing this a few times do you know what to look for.

  • #5

the error always seems to be the outer nest

I’ve always wondered why vba shows the wrong message. I think this clarifies my doubt.

theDBguy

  • #6

I’ve always wondered why vba shows the wrong message. I think this clarifies my doubt.

On the other hand, I think it’s actually giving you the correct message. Of course, I am only guessing, but I believe the VBA interpreter/compiler is reading your code from top to bottom and probably went like this:

Code:

Do While Not ... (compiler: Ah, we're starting a Do loop, need to keep an eye out for the closing Loop keyword)
    For j = ... (compiler: Ah, now we're starting a For/Next loop, need to keep an eye out for the closing Next keyword)
        If rs2.Fields ... (compiler: Ah, this time we're starting an If/Then block, need to keep an eye out for the closing End If statement)
            store = store & ... (compiler: nothing wrong here, just move on)
        Else (compiler: I haven't seen the End If yet, so this Else statement is okay)
        End If (compiler: Ah, here's the end of the If/Then block)
        
        rs2.MoveNext (compiler: This should be legal within the For/Next loop, proceed)
        Loop (compiler: Wait a minute, I didn't see a beginning Do statement inside the For/Next loop, this must be a mistake. Show error message)
[here's the rest of the code that's missing from the original post]
    Next
Loop

See how the indentation helps see the problem? I certainly hope so. Cheers!

  • #7

On the other hand, I think it’s actually giving you the correct message. Of course, I am only guessing, but I believe the VBA interpreter/compiler is reading your code from top to bottom and probably went like this:

Code:

Do While Not ... (compiler: Ah, we're starting a Do loop, need to keep an eye out for the closing Loop keyword)
    For j = ... (compiler: Ah, now we're starting a For/Next loop, need to keep an eye out for the closing Next keyword)
        If rs2.Fields ... (compiler: Ah, this time we're starting an If/Then block, need to keep an eye out for the closing End If statement)
            store = store & ... (compiler: nothing wrong here, just move on)
        Else (compiler: I haven't seen the End If yet, so this Else statement is okay)
        End If (compiler: Ah, here's the end of the If/Then block)
       
        rs2.MoveNext (compiler: This should be legal within the For/Next loop, proceed)
        Loop (compiler: Wait a minute, I didn't see a beginning Do statement inside the For/Next loop, this must be a mistake. Show error message)
[here's the rest of the code that's missing from the original post]
    Next
Loop

See how the indentation helps see the problem? I certainly hope so. Cheers!

I’m sorry but I can’t understand your point. Here’s a simplified version of your code used above:

Code:

Sub test()
    Do While Not f = 0
        For j = 1 To 10
            Loop
        Next
    Loop
End Sub

Vba gives me Loop without DO error and the error message makes sense. Because I don’t have a matching Do/loop.

But in case of OP’s question or similar problems I’ve had before, the message says there’s a problem with loop. While actually loop is OK and the problem is For without Next.

The_Doc_Man

  • #8

@FahadTiger — I will explain your error message. In that explanation, I SHOULD use code tags but I can’t colorize them so I’ll do something else.

Do While Not rs2.EOF
For j = LBound(MYarray) To UBound(MYarray)

If rs2.Fields(«ISSUE»).Value = MYarray(j) Then
store = store & «,» & rs2.Fields(«ENGINEER»).Value
Else
End If

rs2.MoveNext
Loop

The DO WHILE … LOOP construct is almost OK — except that the FOR loop construct is incomplete. More specifically, the FOR J=… loop is unterminated. The correct termination would be to put a NEXT J just below the rs2.MoveNext instruction. You would NOT use a simple NEXT statement because that is not the correct termination. The syntax of VBA FOR «stepping» loops requires that you not only have the stepping variable in the FOR statement but ALSO in the NEXT statement.

This error is due to the «code block» concept. I colorized to show the different blocks. The IF/THEN/ELSE/END IF block in PURPLE is perfectly legal and properly terminated (though you could omit the ELSE and it wouldn’t change anything.) This is not the cause of the problem.

The GREEN block is unterminated because of not having the NEXT J in place. Therefore, the LOOP statement doesn’t have a corresponding DO statement

in the same code block

. My colors show what you probably intended, but using the code block concept, that LOOP statement appears (to VBA) to be in the GREEN block even though the corresponding DO WHILE was in the RED block. Thus, in the block where it appears, you have a LOOP without a DO. Adding the NEXT J before the LOOP statement would close out the GREEN block and leave you back in the RED block where the LOOP would properly terminate the DO.

Just one more side note: rs2.Fields(«ISSUE»).Value is a bit torturous. You could have used rs2![ISSUE] just as easily. Ditto for the [Engineer] field. Turns out that for anything that HAS a .Value property, it is the default property and thus does not need to be expressed. AND if that recordset has a field named ISSUE or one called ENGINEER, then the rs2![fieldname] syntax gets you there without quite as much typing. Again, you can omit the FIELDS() element because the default property for a recordset IS the FIELDS collection.

  • #9

Can anyone tell me why I get an error message «loop without do»? for this code

Code:

Do While Not rs2.EOF
For j = LBound(MYarray) To UBound(MYarray)
If rs2.Fields("ISSUE").Value = MYarray(j) Then
store = store & "," & rs2.Fields("ENGINEER").Value
Else
End If
next j
rs2.MoveNext
Loop
''some actions with a variable

debug.print store
  • #10

I love the way the DBGuy’s compiler gives a satisfied «ah» every time it encounters an understandable piece of code. I hope my compiler is enjoying itself even half as much.

  • #11

you still need the movenext otherwise rs2 will never reach EOF. And you need the next for the j

Code:

Do While Not rs2.EOF
        For j = LBound(MYarray) To UBound(MYarray)
            If rs2.Fields("ISSUE").Value = MYarray(j) Then
                store = store & "," & rs2.Fields("ENGINEER").Value
            Else
            End If
            rs2.movenext
        Next j
Loop

thanks,its solve it

  • #12

more simplistically the way I think of it is — from the original code

Code:

Sub test()
    Do While Not f = 0---compiler says OK starting a loop
        For j = 1 To 10---compiler says OK  starting a loop
            code
        
    Loop---compiler looks back as far as the last 'loop start' and can't see a Do
End Sub
  • #13

Code:

Sub test()
     
    Loop---compiler looks back as far as the last 'loop start' and can't see a Do
End Sub

Sorry but I can’t understand this. You have a Do on line 2. Why compiler can’t see it?

If I was the compiler I would think this way:

Code:

Sub test()
    Do While Not f = 0---compiler says OK starting a loop
        For j = 1 To 10---compiler says OK  starting a loop
            code
    
    Loop---compiler says I reached the loop for Do on line 2 but there's no next. 
                                       Do and For are overlapping. Send a message For without Next
End Sub--

Last edited: Apr 27, 2022

MajP

MajP

You’ve got your good things, and you’ve got mine.
  • #14

The correct termination would be to put a NEXT J just below the rs2.MoveNext instruction. You would NOT use a simple NEXT statement because that is not the correct termination. The syntax of VBA FOR «stepping» loops requires that you not only have the stepping variable in the FOR statement but ALSO in the NEXT statement

This is not correct. VBA is very loose on this construct. No variable is needed in the NEXT. The below runs fine.

SQL:

Public Sub TestLoop()
  Dim rs As DAO.Recordset
  Dim i As Integer
  Dim j As Integer
  Dim fld As DAO.Field
 
  Set rs = CurrentDb.OpenRecordset("01Schools", dbOpenDynaset)
 
  For Each fld In rs.Fields
    For i = 1 To 3
      For j = 1 To 4
        Debug.Print fld.Name & " I: " & i & " J:" & j
      Next
    Next
  Next
End Sub
  • #15

You have a Do on line 2. Why compiler can’t see it?

My thinking is based on how the compiler actually works, not how you think it should work. whether you use for-next, while-loop, etc, they are all loops — the compiler just looks for the start of a loop, not the one that ‘matches’.

If it could, then the error would be on the previous line (where next is missing) but when it reaches that point it doesn’t know that is where the ‘next’ should be so cannot generate an error.

If it compiled in a different way accounting for the different loop types you might have —
started a ‘do’ loop so keep an eye out for the ‘loop’ terminator
now started a ‘for’ loop so keep an eye out for the ‘next’ terminator
now started another ‘for’ loop so keep an eye out for another ‘next’ loop
found the ‘loop’ terminator but hey, haven’t seen a ‘next’ terminator so which ‘for’ is missing a ‘next’?

and now you have the problem — there are two for/next loops and the developer has missed the first next. So when the compiler reaches a next — which for is it applied to?

  • #16

and now you have the problem — there are two for/next loops and the developer has missed the first next. So when the compiler reaches a next — which for is it applied to?

I think I understand your logic now.
But think it this way : In the following line,

Debug.Print Left(myvar, Len(Replace(var2, «_», «») — Len(var2))) & Mid(var2, Len(var2) — Len(var1))

the compiler has an eye on all opening and closing parentheses and quotation marks.
Not only it counts the number of closing and opening parentheses, but also checks for matching pairs and weather they are in the right position.

Why the compiler can not do the same for loops?

If my memory serves me well (which recently doesn’t) long long time ago, when I wrote php, the compiler was able to spot which inner loop has not a matching pair and highlighted the block. Then I was using Zend editor. I wonder why VBA behaves the way you explained.

Last edited: Apr 27, 2022

  • #17

This is not correct. VBA is very loose on this construct. No variable is needed in the NEXT. The below runs fine.

Doc is reminiscing about his BASIC days…

  • #18

I wonder why VBA behaves the way you explained.

More correctly: «I wonder why VBA (mis)behaves the way you explained.»

Last edited: Apr 27, 2022

  • #19

the compiler has an eye on all opening and closing parentheses and quotation marks.
Not only it counts the number of closing and opening parentheses, but also checks for matching pairs and weather they are in the right position.

I would suggest because that is all one line of code so will be compiled in one go.

Thinking ‘out loud’ they belong to functions with parameters separated by commas so the compiler knows how many parameters the function has so it knows where to expect to find the closing parentheses.

And before you mention optional and paramarray parameters I would say it knows the minimum number of commas so expects a closing parentheses after that. With nested functions, it still remains a relatively simple algorithm to keep track.

When you get a compile error — does it actually tell you which closing parentheses is missing?

Within a loop it is anyone’s guess as to where the loop ends until the code says so.

Edit: FYI I have developed a sql editor/management app (being demoed tomorrow at Devcon) and I use a similar method to the above to track what is between single and double quotes and other pairings for the purposes of formatting

The_Doc_Man

  • #20

MajP said: This is not correct. VBA is very loose on this construct. No variable is needed in the NEXT. The below runs fine.

From the Microsoft VBA Language Specification published 04-30-2014, top of page 77 (in the PDF version thereof), and in section 5.4.2.3 For Statement I offer a couple of excerpts.

Code:

for-statement = simple-for-statement / explicit-for-statement
simple-for-statement = for-clause EOS statement-block "Next"
explicit-for-statement = for-clause EOS statement-block ("Next" / (nested-for-statement ",")) bound-variable-expression
nested-for-statement = explicit-for-statement / explicit-for-each-statement
for-clause = "For" bound-variable-expression "=" start-value "To" end-value [stepclause]
start-value = expression
end-value = expression
step-clause = Step" step-increment
step-increment = expression

The <bound-variable-expression> within the <for-clause> of an <explicit-for-statement> must resolve to the same variable as the <bound-variable-expression> following the <statement-block>. The declared type of <bound-variable-expression> must be a numeric value type or Variant.

I didn’t pluck my comment out of thin air. The presence of code tags means I cannot colorize or change much else, so I must simply refer you to the definition for the explicit-for-statement and the for-clause. According to the strict definition of a FOR statement, you have the «FOR variable = …» part followed by the statement block followed by Next and, if there is no intervening loop, the bound variable expression as in «NEXT variable» — and further, the variable with NEXT must resolve to the same variable as was used in the FOR statement.

I think we must at least agree that the FOR loop lacked proper termination. Whether by NEXT or NEXT J, it needed something it didn’t have, and the rest of my explanation (about implied language blocks) was correct. @MajP, you may indeed be correct that newer versions of VBA are looser than used to be the case. However, if the OP is using Access before 2016, this standard should apply.

NG said: Doc is reminiscing about his BASIC days…

Actually, no. As it happens, I am quoting the strict statement that describes VBA syntax, and I have named the reference. It is too big for me to upload in its entirety and besides, you can look it up yourself if you have an urgent need to do so. The following link gives you a page to download PDF or WORD versions from 2014 through 2021.

docs.microsoft.com

[MS-VBAL]: VBA Language Specification

Specifies the VBA Language, which defines the implementation-independent and operating system-independent programming language that is required

docs.microsoft.com

I looked at the 2021 version for the FOR statement and the language definition has not changed. It does not indicate that the bound variable of the NEXT is optional. More precisely, the syntax of the language definition doesn’t include a «leave it blank» option.

Выдает ошибку «Loop without Do» хотя Do есть

Bamboo

Дата: Понедельник, 28.03.2016, 21:50 |
Сообщение № 1

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

Ранг: Участник

Сообщений: 99


Репутация:

0

±

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


Excel 2010

Странная ситуация, цикл исправно работал. А Потом появилась эта ошибка. Хотя Do есть.
Прошу не ругаться на код, это мой первый на VBA да еще и не отлаженный.
[vba]

Код

Function HighLevACC(ACC, DistMap)
Dim Array_DistMap()
Dim Array_SubHLACC()
Dim I As Integer, J As Integer, X As Integer, Y As Integer
Do
X = X + 1
If ACC.Cells(X, 1) = «Empty» And ThisCell.Address.Offset(X, 10) = «» Then      
Set vHLACC = ACC.Cells(X, -1)
Array_DistMap = DistMap.Value
  Counter_j = 0
For I = 1 To UBound(Array_DistMap)
If Array_DistMap(I, 1) = vHLACC Then
J = J + 1
ReDim Preserve Array_SubHLACC(1 To J)
Array_SubHLACC(J) = Array_DistMap(I, 2)
  MsgBox (Array_SubHLACC(J))
  End If
Next
HighLevACC = Array_SubHLACC(2)
HighLevACC.Offset(0, 9) = 1
ACC.Cells(Õ, 9) = «S»      
If ACC.Cells(Õ — 1, 10) = «C» Then       
vHLACC = ACC.Cells(X — 1, -1)
Counter_j = 0
For I = 1 To UBound(Array_DistMap)
If Array_DistMap(I, 1) = vHLACC Then
J = J + 1
ReDim Preserve Array_SubHLACC(0 To J)
Array_SubHLACC(J) = Array_DistMap(I, 2)
  End If
Next
Y = HighLevACC.Offcet(-1, 9)
Y = Y + 1
If Y <= J Then
HighLevACC = Array_SubHLACC(Y)
HighLevACC.Cells(0, 9) = Y
If Y = J Then
HighLevACC.Cells(0, 10) = «D»
End If
End If
End If
HighLevACC = ACC.Cells(X, 1)
Loop While (X < ACC.Count) Or (ACC.Cells(X, 1) = «Empty» And ThisCell.Address.Offset(X, 10) = «»)
End Function

[/vba]

 

Ответить

al-Ex

Дата: Понедельник, 28.03.2016, 22:00 |
Сообщение № 2

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 190


Репутация:

59

±

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


Excel 2010


если цикл начинается с «For I =1 …» тогда уже внизу — «Next I», исправьте в двух местах.
и конструкции типа: If Then
Else
End If
так мудрёно лучше не делать.
Вряд-ли это будет работать именно так как Вы задумали.

Сообщение отредактировал al-ExПонедельник, 28.03.2016, 22:24

 

Ответить

Невилл

Дата: Понедельник, 28.03.2016, 22:09 |
Сообщение № 3

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

Ранг: Участник

Сообщений: 79


Репутация:

2

±

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


Excel 2007

Одно из If не закрыто.

Кстати, неплохо бы определять переменные и их типы сверху, пожалуй.

 

Ответить

Апострофф

Дата: Понедельник, 28.03.2016, 22:10 |
Сообщение № 4

Группа: Проверенные

Ранг: Обитатель

Сообщений: 416


Репутация:

117

±

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


Excel 1997

Учитесь оформлять код отступами — и проблем не будет
[vba]

Код

Function HighLevACC(ACC, DistMap)
Dim Array_DistMap()
Dim Array_SubHLACC()
Dim I As Integer, J As Integer, X As Integer, Y As Integer
Do
    X = X + 1
    If ACC.Cells(X, 1) = «Empty» And ThisCell.Address.Offset(X, 10) = «» Then
        Set vHLACC = ACC.Cells(X, -1)
        Array_DistMap = DistMap.Value
        Counter_j = 0
        For I = 1 To UBound(Array_DistMap)
            If Array_DistMap(I, 1) = vHLACC Then
                J = J + 1
                ReDim Preserve Array_SubHLACC(1 To J)
                Array_SubHLACC(J) = Array_DistMap(I, 2)
                MsgBox (Array_SubHLACC(J))
            End If
        Next
        HighLevACC = Array_SubHLACC(2)
        HighLevACC.Offset(0, 9) = 1
        ACC.Cells(O, 9) = «S»
        If ACC.Cells(O — 1, 10) = «C» Then
            vHLACC = ACC.Cells(X — 1, -1)
            Counter_j = 0
            For I = 1 To UBound(Array_DistMap)
                If Array_DistMap(I, 1) = vHLACC Then
                    J = J + 1
                    ReDim Preserve Array_SubHLACC(0 To J)
                    Array_SubHLACC(J) = Array_DistMap(I, 2)
                End If
            Next
            Y = HighLevACC.Offcet(-1, 9)
            Y = Y + 1
            If Y <= J Then
                HighLevACC = Array_SubHLACC(Y)
                HighLevACC.Cells(0, 9) = Y
                If Y = J Then
                    HighLevACC.Cells(0, 10) = «D»
                End If
            End If
        End If
    End If ‘НЕ ХВАТАЛО ЭТОГО.
    HighLevACC = ACC.Cells(X, 1)
Loop While (X < ACC.Count) Or (ACC.Cells(X, 1) = «Empty» And ThisCell.Address.Offset(X, 10) = «»)
End Function

[/vba]

Сообщение отредактировал АпостроффПонедельник, 28.03.2016, 22:18

 

Ответить

Bamboo

Дата: Понедельник, 28.03.2016, 22:48 |
Сообщение № 5

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

Ранг: Участник

Сообщений: 99


Репутация:

0

±

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


Excel 2010

Апострофф, Спасибо! Получилось! Насчет, отступов, это я поленился, а зря…

 

Ответить

_Boroda_

Дата: Понедельник, 28.03.2016, 23:02 |
Сообщение № 6

Группа: Модераторы

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

Сообщений: 16618


Репутация:

6465

±

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


2003; 2007; 2010; 2013 RUS

Bamboo, Виталий, я, например, делаю вот так — когда пишу If … Then, то сразу же ДВА раза жму Ентер и пишу End If, затем возвращаюсь на строчку выше, жму Тав и пишу то, что хотел написать внутри Ифа.
Аналогично с циклами — For i = 1 to 5, ДВА раза Ентер, Next i, стрелка вверх, Тав и тело цикла. При таком стиле записи я уже не теряю закрытия циклов и Ifов.
Можно еще пользоваться облегчениями отсюда http://www.excelworld.ru/forum/10-22392-180576-16-1458977793
Кстати, вот это

если цикл начинается с «For I =1 …» тогда уже внизу — «Next I»

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

Насчет, отступов, это я поленился

Отступы легко делать Тавом или в VBA вывести панельку Edit, там есть специальные кнопочки — ими можно делать отступ сразу для нескольких строк (Тавом тоже можно).


Скажи мне, кудесник, любимец ба’гов…
Платная помощь:
Boroda_Excel@mail.ru
Яндекс-деньги: 41001632713405 | Webmoney: R289877159277; Z102172301748; E177867141995

 

Ответить

Доброго времени суток.  

  Задумка такова:  

  1. Установить счётчик строк на 38.  
2. Если ячейка в столбце А (строка — по счётчику) не пустая, выполнить п.3-5. Если пустая, остановить программу.  
3. Если ячейка в определённом столбце той же строки имеет значение «Оплачено», изменить цвет шрифта в ячейке столбца А той же строки. Если нет, перейти к п.4.  
4. Увеличить счётчик строк на единицу.  
5. Перейти к п.2  

  Код:  

  Sub Hilight ()  
Dim taskcell as Integer  
taskcell = 38  
Do Until Range(«A» & taskcell).Value = «»  
If Range(«A» & taskcell).Offset(0, 2 + User) = («Оплачено») Then  
   Range(«A» & taskcell).Font.ColorIndex = 16  
   Else  
   taskcell = taskcell + 1  
Loop  
End Sub  

  При запуске выдаётся сообщение «Compile error: Loop without Do». Помогите понять ошибку.

zzoommmmmm

0 / 0 / 0

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

Сообщений: 6

1

13.12.2011, 17:58. Показов 6867. Ответов 3

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


Студворк — интернет-сервис помощи студентам

Найти первый отрицательный член последовательности cos(ctg(n)) для n изменяющегося следующим образом: n = 1, 2, 3, … .

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
Sub Tim()
Dim n As Integer
Dim Y As Integer
n = 1
Do
    Y = Cos(1 / Tan(n))
    If Y < 0 Then
    Debug.Print "n="; n, "Y="; Y: GoTo M
    Else
    n = n + 1
Loop While Y >= 0
M:     End If
End Sub

Помогите исправить код, пишет ошибку «Loop without Do». Заранее спасибо!)

0

Programming

Эксперт

94731 / 64177 / 26122

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

Сообщений: 116,782

13.12.2011, 17:58

Ответы с готовыми решениями:

Почему в коде указано, что » кнопка 1 » и » кнопка 2 » добавлены в центр, а они добавляются «по умолчанию»?
Вот мой код:

import java.awt.*;

import javax.swing.*;

@SuppressWarnings(&quot;serial&quot;)…

В строке все буквы «а» заменить буквой «б» и наоборот, если они есть
В строке все буквы &quot;а&quot; заменить буквой &quot;б&quot; и наоборот, если они есть

Составьте программу, выясняющую, есть ли в слове Х хотя бы одна из букв «о» или «а»
1. Составьте программу, выясняющую, есть ли в слове Х хотя бы одна из букв &quot;о&quot; или &quot;а&quot;.
2….

Выясните, есть ли в слове X хотя бы одна из букв «к» или «м»
Выясните, есть ли в слове X хотя бы одна из букв &quot;к&quot; или &quot;м&quot;.

3

es geht mir gut

11264 / 4746 / 1183

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

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

13.12.2011, 18:20

2

11 и 12 строку поменяй местами, у меня был точно такой же случай.
А в 8 поставь не Go To M, а Exit Do

1

Alex77755

11478 / 3770 / 676

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

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

13.12.2011, 18:25

3

Цитата
Сообщение от SoftIce.net
Посмотреть сообщение

11 и 12 строку поменяй местами, у меня был точно такой же случай.
А в 8 поставь не Go To M, а Exit Do

Вообще убери. Уже есть условие

Visual Basic
1
While Y >= 0

1

0 / 0 / 0

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

Сообщений: 6

13.12.2011, 18:25

 [ТС]

4

Цитата
Сообщение от SoftIce.net
Посмотреть сообщение

11 и 12 строку поменяй местами, у меня был точно такой же случай.
А в 8 поставь не Go To M, а Exit Do

Спасибо, помогло)

0

IT_Exp

Эксперт

87844 / 49110 / 22898

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

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

13.12.2011, 18:25

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

Выясните, есть ли в слове Х хотя бы одна из букв «о» или «а»
№1) Выясните, есть ли в слове Х хотя бы одна из букв &quot;о&quot; или &quot;а&quot;.

Дана строка, состоящая из слов, разделенных пробелом. Определить количество слов, в которых есть хотя бы одна буква «а», или «А»
Дана строка, состоящая из слов, разделенных пробелом. Определить количество слов, в которых есть…

Непонятная ошибка » For loop control variable must have ordinal type»
unit Unit3;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics,…

Патерн «прототип» не работает, выдаёт ошибку «недопустимый вызов нестатической ф-ции», где я в коде ошибка?
Вот мой код…

#include &lt;iostream&gt;
#include &lt;Windows.h&gt;
#include &lt;vector&gt;
#define vrom…

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

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

4

I’m trying to create a VBA to open all files in a folder, copy the sheet named «Weekly Forecast» and place it into the tab named after the file…. [File name «Weekly Forecast E0462» tab «E0462» : File name «Weekly Forecast E1262» tab «E1262» for example]

 Ive got the vba below and it looks like it would work…but I keep getting a Loop without Do bug error.
 Can someone help ?

Sub LoopAllExcelFilesInFolder()

Dim wb As Workbook
Dim ws As Worksheet
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim buf As String
Dim shn As String
Dim x As Workbook
Dim y As Workbook
Set x = Workbooks.Open(Filename:=myPath & myFile)
Set y = Workbooks("Weekly_Forecast_Dashboard.xlsm")
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "C:Users10053845DesktopTrialSource Files"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & ""
End With
Set wb = Workbooks("Weekly_Forecast_Dashboard.xlsm")
'In Case of Cancel
NextCode:
myPath = wb.Path & "/"
buf = Dir(myPath & "Weekly_Forecast_E*.XLsx")
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"
'Target Path with Ending Extention
MyFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While buf <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
Set ws = Workbooks.Open(myPath & buf).Sheets("Weekly Forecast")
shn = Mid(Split(buf, "_")(2), 1, 5)

'Ensure Workbook has opened before moving on to next line of code
DoEvents

'Copy Selected range
With wb.Worksheets(shn)
.Range("B22:H46").Value = ws.Range("B22:H46").Value
.Range("J22:J46").Value = ws.Range("J22:J46").Value
.Range("B69:H71").Value = ws.Range("B69:H71").Value
.Range("J69:J71").Value = ws.Range("J69:J71").Value
.Range("B75:H77").Value = ws.Range("B75:H77").Value
.Range("J75:J77").Value = ws.Range("J75:J77").Value

'Save and Close Workbook
wb.Close SaveChanges:=True

'Ensure Workbook has closed before moving on to next line of code
DoEvents
'Get next file name
myFile = Dir
Loop

'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub

Open in new window

(Edit: Added CODE tags)

  • #1

hi experts….
Can anyone tell me why I get an error message «loop without do»? for this code

Code:

Do While Not rs2.EOF
        For j = LBound(MYarray) To UBound(MYarray)
            If rs2.Fields("ISSUE").Value = MYarray(j) Then
                store = store & "," & rs2.Fields("ENGINEER").Value
            Else
            End If
            rs2.MoveNext
Loop
  • #2

hi experts….
Can anyone tell me why I get an error message «loop without do»? for this code

Code:

Do While Not rs2.EOF
        For j = LBound(MYarray) To UBound(MYarray)
            If rs2.Fields("ISSUE").Value = MYarray(j) Then
                store = store & "," & rs2.Fields("ENGINEER").Value
            Else
            End If
            rs2.MoveNext
Loop

Try using a Next statement instead of MoveNext. Is this all the code? Are you opening a recordset first and then executing these lines? Just asking.

Code:

Do While Not rs2.EOF
        For j = LBound(MYarray) To UBound(MYarray)
            If rs2.Fields("ISSUE").Value = MYarray(j) Then
                store = store & "," & rs2.Fields("ENGINEER").Value
            Else
            End If
        Next
Loop
  • #3

you still need the movenext otherwise rs2 will never reach EOF. And you need the next for the j

Code:

Do While Not rs2.EOF
        For j = LBound(MYarray) To UBound(MYarray)
            If rs2.Fields("ISSUE").Value = MYarray(j) Then
                store = store & "," & rs2.Fields("ENGINEER").Value
            Else
            End If
            rs2.movenext
        Next j
Loop

MajP

MajP

You’ve got your good things, and you’ve got mine.
  • #4

Can anyone tell me why I get an error message «loop without do»? for this code

If you have a broken construct (IF without END IF, Do without Loop, For without Next) and they are nested the error always seems to be the outer nest and not the construct with the actual problem. So the message always seems wrong.
In this case it is broken because you have a FOR without a Next inside the DO Loop. You would expect the error to be FOR WITHOUT NEXT, not LOOP Without DO. Only after seeing this a few times do you know what to look for.

  • #5

the error always seems to be the outer nest

I’ve always wondered why vba shows the wrong message. I think this clarifies my doubt.

theDBguy

  • #6

I’ve always wondered why vba shows the wrong message. I think this clarifies my doubt.

On the other hand, I think it’s actually giving you the correct message. Of course, I am only guessing, but I believe the VBA interpreter/compiler is reading your code from top to bottom and probably went like this:

Code:

Do While Not ... (compiler: Ah, we're starting a Do loop, need to keep an eye out for the closing Loop keyword)
    For j = ... (compiler: Ah, now we're starting a For/Next loop, need to keep an eye out for the closing Next keyword)
        If rs2.Fields ... (compiler: Ah, this time we're starting an If/Then block, need to keep an eye out for the closing End If statement)
            store = store & ... (compiler: nothing wrong here, just move on)
        Else (compiler: I haven't seen the End If yet, so this Else statement is okay)
        End If (compiler: Ah, here's the end of the If/Then block)
        
        rs2.MoveNext (compiler: This should be legal within the For/Next loop, proceed)
        Loop (compiler: Wait a minute, I didn't see a beginning Do statement inside the For/Next loop, this must be a mistake. Show error message)
[here's the rest of the code that's missing from the original post]
    Next
Loop

See how the indentation helps see the problem? I certainly hope so. Cheers!

  • #7

On the other hand, I think it’s actually giving you the correct message. Of course, I am only guessing, but I believe the VBA interpreter/compiler is reading your code from top to bottom and probably went like this:

Code:

Do While Not ... (compiler: Ah, we're starting a Do loop, need to keep an eye out for the closing Loop keyword)
    For j = ... (compiler: Ah, now we're starting a For/Next loop, need to keep an eye out for the closing Next keyword)
        If rs2.Fields ... (compiler: Ah, this time we're starting an If/Then block, need to keep an eye out for the closing End If statement)
            store = store & ... (compiler: nothing wrong here, just move on)
        Else (compiler: I haven't seen the End If yet, so this Else statement is okay)
        End If (compiler: Ah, here's the end of the If/Then block)
       
        rs2.MoveNext (compiler: This should be legal within the For/Next loop, proceed)
        Loop (compiler: Wait a minute, I didn't see a beginning Do statement inside the For/Next loop, this must be a mistake. Show error message)
[here's the rest of the code that's missing from the original post]
    Next
Loop

See how the indentation helps see the problem? I certainly hope so. Cheers!

I’m sorry but I can’t understand your point. Here’s a simplified version of your code used above:

Code:

Sub test()
    Do While Not f = 0
        For j = 1 To 10
            Loop
        Next
    Loop
End Sub

Vba gives me Loop without DO error and the error message makes sense. Because I don’t have a matching Do/loop.

But in case of OP’s question or similar problems I’ve had before, the message says there’s a problem with loop. While actually loop is OK and the problem is For without Next.

The_Doc_Man

  • #8

@FahadTiger — I will explain your error message. In that explanation, I SHOULD use code tags but I can’t colorize them so I’ll do something else.

Do While Not rs2.EOF
For j = LBound(MYarray) To UBound(MYarray)

If rs2.Fields(«ISSUE»).Value = MYarray(j) Then
store = store & «,» & rs2.Fields(«ENGINEER»).Value
Else
End If

rs2.MoveNext
Loop

The DO WHILE … LOOP construct is almost OK — except that the FOR loop construct is incomplete. More specifically, the FOR J=… loop is unterminated. The correct termination would be to put a NEXT J just below the rs2.MoveNext instruction. You would NOT use a simple NEXT statement because that is not the correct termination. The syntax of VBA FOR «stepping» loops requires that you not only have the stepping variable in the FOR statement but ALSO in the NEXT statement.

This error is due to the «code block» concept. I colorized to show the different blocks. The IF/THEN/ELSE/END IF block in PURPLE is perfectly legal and properly terminated (though you could omit the ELSE and it wouldn’t change anything.) This is not the cause of the problem.

The GREEN block is unterminated because of not having the NEXT J in place. Therefore, the LOOP statement doesn’t have a corresponding DO statement

in the same code block

. My colors show what you probably intended, but using the code block concept, that LOOP statement appears (to VBA) to be in the GREEN block even though the corresponding DO WHILE was in the RED block. Thus, in the block where it appears, you have a LOOP without a DO. Adding the NEXT J before the LOOP statement would close out the GREEN block and leave you back in the RED block where the LOOP would properly terminate the DO.

Just one more side note: rs2.Fields(«ISSUE»).Value is a bit torturous. You could have used rs2![ISSUE] just as easily. Ditto for the [Engineer] field. Turns out that for anything that HAS a .Value property, it is the default property and thus does not need to be expressed. AND if that recordset has a field named ISSUE or one called ENGINEER, then the rs2![fieldname] syntax gets you there without quite as much typing. Again, you can omit the FIELDS() element because the default property for a recordset IS the FIELDS collection.

  • #9

Can anyone tell me why I get an error message «loop without do»? for this code

Code:

Do While Not rs2.EOF
For j = LBound(MYarray) To UBound(MYarray)
If rs2.Fields("ISSUE").Value = MYarray(j) Then
store = store & "," & rs2.Fields("ENGINEER").Value
Else
End If
next j
rs2.MoveNext
Loop
''some actions with a variable

debug.print store
  • #10

I love the way the DBGuy’s compiler gives a satisfied «ah» every time it encounters an understandable piece of code. I hope my compiler is enjoying itself even half as much.

  • #11

you still need the movenext otherwise rs2 will never reach EOF. And you need the next for the j

Code:

Do While Not rs2.EOF
        For j = LBound(MYarray) To UBound(MYarray)
            If rs2.Fields("ISSUE").Value = MYarray(j) Then
                store = store & "," & rs2.Fields("ENGINEER").Value
            Else
            End If
            rs2.movenext
        Next j
Loop

thanks,its solve it

  • #12

more simplistically the way I think of it is — from the original code

Code:

Sub test()
    Do While Not f = 0---compiler says OK starting a loop
        For j = 1 To 10---compiler says OK  starting a loop
            code
        
    Loop---compiler looks back as far as the last 'loop start' and can't see a Do
End Sub
  • #13

Code:

Sub test()
     
    Loop---compiler looks back as far as the last 'loop start' and can't see a Do
End Sub

Sorry but I can’t understand this. You have a Do on line 2. Why compiler can’t see it?

If I was the compiler I would think this way:

Code:

Sub test()
    Do While Not f = 0---compiler says OK starting a loop
        For j = 1 To 10---compiler says OK  starting a loop
            code
    
    Loop---compiler says I reached the loop for Do on line 2 but there's no next. 
                                       Do and For are overlapping. Send a message For without Next
End Sub--

Last edited: Apr 27, 2022

MajP

MajP

You’ve got your good things, and you’ve got mine.
  • #14

The correct termination would be to put a NEXT J just below the rs2.MoveNext instruction. You would NOT use a simple NEXT statement because that is not the correct termination. The syntax of VBA FOR «stepping» loops requires that you not only have the stepping variable in the FOR statement but ALSO in the NEXT statement

This is not correct. VBA is very loose on this construct. No variable is needed in the NEXT. The below runs fine.

SQL:

Public Sub TestLoop()
  Dim rs As DAO.Recordset
  Dim i As Integer
  Dim j As Integer
  Dim fld As DAO.Field
 
  Set rs = CurrentDb.OpenRecordset("01Schools", dbOpenDynaset)
 
  For Each fld In rs.Fields
    For i = 1 To 3
      For j = 1 To 4
        Debug.Print fld.Name & " I: " & i & " J:" & j
      Next
    Next
  Next
End Sub
  • #15

You have a Do on line 2. Why compiler can’t see it?

My thinking is based on how the compiler actually works, not how you think it should work. whether you use for-next, while-loop, etc, they are all loops — the compiler just looks for the start of a loop, not the one that ‘matches’.

If it could, then the error would be on the previous line (where next is missing) but when it reaches that point it doesn’t know that is where the ‘next’ should be so cannot generate an error.

If it compiled in a different way accounting for the different loop types you might have —
started a ‘do’ loop so keep an eye out for the ‘loop’ terminator
now started a ‘for’ loop so keep an eye out for the ‘next’ terminator
now started another ‘for’ loop so keep an eye out for another ‘next’ loop
found the ‘loop’ terminator but hey, haven’t seen a ‘next’ terminator so which ‘for’ is missing a ‘next’?

and now you have the problem — there are two for/next loops and the developer has missed the first next. So when the compiler reaches a next — which for is it applied to?

  • #16

and now you have the problem — there are two for/next loops and the developer has missed the first next. So when the compiler reaches a next — which for is it applied to?

I think I understand your logic now.
But think it this way : In the following line,

Debug.Print Left(myvar, Len(Replace(var2, «_», «») — Len(var2))) & Mid(var2, Len(var2) — Len(var1))

the compiler has an eye on all opening and closing parentheses and quotation marks.
Not only it counts the number of closing and opening parentheses, but also checks for matching pairs and weather they are in the right position.

Why the compiler can not do the same for loops?

If my memory serves me well (which recently doesn’t) long long time ago, when I wrote php, the compiler was able to spot which inner loop has not a matching pair and highlighted the block. Then I was using Zend editor. I wonder why VBA behaves the way you explained.

Last edited: Apr 27, 2022

  • #17

This is not correct. VBA is very loose on this construct. No variable is needed in the NEXT. The below runs fine.

Doc is reminiscing about his BASIC days…

  • #18

I wonder why VBA behaves the way you explained.

More correctly: «I wonder why VBA (mis)behaves the way you explained.»

Last edited: Apr 27, 2022

  • #19

the compiler has an eye on all opening and closing parentheses and quotation marks.
Not only it counts the number of closing and opening parentheses, but also checks for matching pairs and weather they are in the right position.

I would suggest because that is all one line of code so will be compiled in one go.

Thinking ‘out loud’ they belong to functions with parameters separated by commas so the compiler knows how many parameters the function has so it knows where to expect to find the closing parentheses.

And before you mention optional and paramarray parameters I would say it knows the minimum number of commas so expects a closing parentheses after that. With nested functions, it still remains a relatively simple algorithm to keep track.

When you get a compile error — does it actually tell you which closing parentheses is missing?

Within a loop it is anyone’s guess as to where the loop ends until the code says so.

Edit: FYI I have developed a sql editor/management app (being demoed tomorrow at Devcon) and I use a similar method to the above to track what is between single and double quotes and other pairings for the purposes of formatting

The_Doc_Man

  • #20

MajP said: This is not correct. VBA is very loose on this construct. No variable is needed in the NEXT. The below runs fine.

From the Microsoft VBA Language Specification published 04-30-2014, top of page 77 (in the PDF version thereof), and in section 5.4.2.3 For Statement I offer a couple of excerpts.

Code:

for-statement = simple-for-statement / explicit-for-statement
simple-for-statement = for-clause EOS statement-block "Next"
explicit-for-statement = for-clause EOS statement-block ("Next" / (nested-for-statement ",")) bound-variable-expression
nested-for-statement = explicit-for-statement / explicit-for-each-statement
for-clause = "For" bound-variable-expression "=" start-value "To" end-value [stepclause]
start-value = expression
end-value = expression
step-clause = Step" step-increment
step-increment = expression

The <bound-variable-expression> within the <for-clause> of an <explicit-for-statement> must resolve to the same variable as the <bound-variable-expression> following the <statement-block>. The declared type of <bound-variable-expression> must be a numeric value type or Variant.

I didn’t pluck my comment out of thin air. The presence of code tags means I cannot colorize or change much else, so I must simply refer you to the definition for the explicit-for-statement and the for-clause. According to the strict definition of a FOR statement, you have the «FOR variable = …» part followed by the statement block followed by Next and, if there is no intervening loop, the bound variable expression as in «NEXT variable» — and further, the variable with NEXT must resolve to the same variable as was used in the FOR statement.

I think we must at least agree that the FOR loop lacked proper termination. Whether by NEXT or NEXT J, it needed something it didn’t have, and the rest of my explanation (about implied language blocks) was correct. @MajP, you may indeed be correct that newer versions of VBA are looser than used to be the case. However, if the OP is using Access before 2016, this standard should apply.

NG said: Doc is reminiscing about his BASIC days…

Actually, no. As it happens, I am quoting the strict statement that describes VBA syntax, and I have named the reference. It is too big for me to upload in its entirety and besides, you can look it up yourself if you have an urgent need to do so. The following link gives you a page to download PDF or WORD versions from 2014 through 2021.

docs.microsoft.com

[MS-VBAL]: VBA Language Specification

Specifies the VBA Language, which defines the implementation-independent and operating system-independent programming language that is required

docs.microsoft.com

I looked at the 2021 version for the FOR statement and the language definition has not changed. It does not indicate that the bound variable of the NEXT is optional. More precisely, the syntax of the language definition doesn’t include a «leave it blank» option.

Понравилась статья? Поделить с друзьями:
  • Ошибка lost connection mysql server during query
  • Ошибка long term fuel trim
  • Ошибка los на роутере ростелеком что это такое
  • Ошибка logitech profiler was unable to detect any
  • Ошибка los на роутере мтс