KeelPM
Пользователь
Сообщений: 8
Регистрация: 21.08.2014
Добрый день уважаемые форумчане.
Учусь самостоятельно работать в VBA, параллельно автоматизирую различные несложные рабочие сценарии.
При написании последнего макроса столкнулся с ошибкой, которую никак не получается исправить, либо найти её причины. Ошибка наверняка очень глупая, либо я просто нарушил какое-то неизвестное мне фундаментальное правило в написании.
К делу. Имеется макрос, который отыскивает на листе «Трафик» в столбце I значения «Ок» или «Внимание». В случае нахождения — копирует некоторые данные строки в которой нашел нужное значение на лист Автоматические тесты» и переходит к следующей строке, пока не дойдет до 60й, на которой его работа заканчивается. Макрос полностью рабочий, вот он.
| Код |
|---|
Sub Razchet()
Dim List As String
Application.ScreenUpdating = False
List = "Трафик"
For x = 12 To 60
Worksheets("Трафик").Activate If Cells(x, 9).Value = "Ок" Or Cells(x, 9).Value = "Внимание" Then
Worksheets("Автоматические тесты").Activate
Cells((x - 1), 11).Value = Worksheets(List).Cells(2, 2)
Cells((x - 1), 12).Value = Worksheets(List).Cells(2, 3)
Cells((x - 1), 13).Value = Worksheets(List).Cells(5, 2)
Cells((x - 1), 14).Select
ActiveCell.FormulaR1C1 = "Высокий"
Cells((x - 1), 15).Value = Worksheets(List).Cells(x, 1)
Cells((x - 1), 16).Value = Worksheets(List).Cells(x, 8)
If Worksheets(List).Cells(x, 9) = "îê" Then
Cells((x - 1), 17).Select
ActiveCell.FormulaR1C1 = "Завершено, ошибок нет" Else:
End If
If Worksheets(List).Cells(x, 9) = "Внимание" Then
Cells((x - 1), 17).Select
ActiveCell.FormulaR1C1 = "Завершено, есть ошибки" Else:
End If
Cells((x - 1), 18).Value = Worksheets(List).Cells(x, 11)
Cells((x - 1), 19).Value = Worksheets(List).Cells(x, 5)
Cells((x - 1), 20).Value = Worksheets(List).Cells(x, 10)
Else:
End If
Next x
End Sub
|
Далее я модернизировал макрос до такого вида:
| Код |
|---|
Sub Razchet()
Dim List As String
Application.ScreenUpdating = False
List = "Трафик"
For x = 12 To 60
For y = 11 To 59
Worksheets("Трафик").Activate If Cells(x, 9).Value = "Ок" Or Cells(x, 9).Value = "Внимание" Then
Worksheets("Автоматические тесты").Activate
Cells(y, 11).Value = Worksheets(List).Cells(2, 2)
Cells(y, 12).Value = Worksheets(List).Cells(2, 3)
Cells(y, 13).Value = Worksheets(List).Cells(5, 2)
Cells(y, 14).Select
ActiveCell.FormulaR1C1 = "Высокий"
Cells(y, 15).Value = Worksheets(List).Cells(x, 1)
Cells(y, 16).Value = Worksheets(List).Cells(x, 8)
If Worksheets(List).Cells(x, 9) = "îê" Then
Cells(y, 17).Select
ActiveCell.FormulaR1C1 = "Завершено, ошибок нет" Else:
End If
If Worksheets(List).Cells(x, 9) = "Внимание" Then
Cells(y, 17).Select
ActiveCell.FormulaR1C1 = "Завершено, есть ошибки" Else:
End If
Cells(y, 18).Value = Worksheets(List).Cells(x, 11)
Cells(y, 19).Value = Worksheets(List).Cells(x, 5)
Cells(y, 20).Value = Worksheets(List).Cells(x, 10)
Else:
End If
Next x
Next y
End Sub
|
и работать он перестал выдавая invalid next variable control reference.
Помогите найти ошибку (и не сильно ругайте если она окажется глупой).
Спасибо!
I’m sorry, i shouldve explained what i was trying to produce than asking to fix something i wanted to do. My experience in vba has been self-taught, and i’m a little new to asking for help.
The script Floris produced seemed to have function but not as intended. Turns out what i wrote is a little outdated, and needs to be wiped and restarted. This was actually an old script i started a few months back that worked off of a web-query. But the website went thru some changes and now the script is all over the place.
the main issue i was having was a compile-error «Invalid Next Control Variable Reference» Which turns out to be caused by an open ‘Do while’ loop, that doesnt seem to have much of an exit point from the research i looked up. Was supposed to have used another ‘If’ command instead. At the same time, when attempting to solve that ‘Do While’ i added an extra ‘Next’ (cause i thought they were compatible), and it screwed with the script.
Hard to explain.. But the ‘Do While’ i used, i wanted it to combine the values only if the number of values were greater
rnumbers = Rows(ActiveCell.Range("A3").End(xlDown)) + 3
'or CellCount = ActiveCell.Range("A" & Rows.Count).End(xldown).Row
Do While Rows(ActiveCell.Range("A3").End(xlDown)) > 3
But instead it was supposed to be
Dim CellCount As Range
CellCount = ActiveCell.Range("A" & Rows.Count).End(xlDown).Row + 2
'cause its the active cell + two additional cells
If CellCount > 3
Which then opens up into the script Floris submitted. (But that failed too, because of what was stated above).
Thanks again, hope that it explains everything… Sorry if i wasted your time with that one Floris, really do appreciate the assistance. Just wish i had asked for the help sooner, would have saved me a lot of frustration that i’m dealing with now. >_>
Permalink
Cannot retrieve contributors at this time
| title | keywords | f1_keywords | ms.prod | ms.assetid | ms.date | ms.localizationpriority |
|---|---|---|---|---|---|---|
|
Invalid Next control variable reference |
vblr6.chm1011226 |
vblr6.chm1011226 |
office |
1fd6eeda-b1e9-5c36-8100-b0e8ea3614fc |
06/08/2017 |
medium |
The numeric variable in the Next part of a For…Next loop must match the variable in the For part. This error has the following cause and solution:
-
The variable in the Next part of a For…Next loop differs from the variable in the For part. For example:
For Counter = 1 To 10 MyVar = Counter Next Count
Check the spelling of the variable in the Next part to be sure it matches the For part. Also, be sure you haven’t inadvertently deleted parts of the enclosing loop that used the variable.
For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).
[!includeSupport and feedback]
Permalink
Cannot retrieve contributors at this time
| title | keywords | f1_keywords | ms.prod | ms.assetid | ms.date | ms.localizationpriority |
|---|---|---|---|---|---|---|
|
Invalid Next control variable reference |
vblr6.chm1011226 |
vblr6.chm1011226 |
office |
1fd6eeda-b1e9-5c36-8100-b0e8ea3614fc |
06/08/2017 |
medium |
The numeric variable in the Next part of a For…Next loop must match the variable in the For part. This error has the following cause and solution:
-
The variable in the Next part of a For…Next loop differs from the variable in the For part. For example:
For Counter = 1 To 10 MyVar = Counter Next Count
Check the spelling of the variable in the Next part to be sure it matches the For part. Also, be sure you haven’t inadvertently deleted parts of the enclosing loop that used the variable.
For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).
[!includeSupport and feedback]
Hi,
I am getting the same ERROR massage for the below code.
Please help in it.
open_db1
open_db2
‘str_key = «SELECT distinct » & str_Query_MailBody & » FROM [MasterData_Domestic_5284$] where » & str_key & «=» & key_data(i)
keylist1 = Fetch_keylist2(str_key)
keycount1 = UBound(VBA.Split(keylist1, «,»)) + 1
key_data1 = VBA.Split(keylist1, «,»)
For i = 0 To keycount1 — 1
strSql = «SELECT » & str_Query_MailBody & » FROM [MasterData_Domestic_5284$] where » & str_key & «=» & key_data1(i)
Set rs1 = db1.OpenRecordset(strSql)
If rs1 Is Nothing Then
MsgBox «Error in All Fails data fetch!», vbExclamation, ThisWorkbook.Name
Exit Sub
End If
‘To Form the page and header
rs1.MoveFirst
rs1.MoveLast
reccount = rs1.RecordCount
rs1.MoveFirst
str = «»
If (Not rs1.EOF) Then
‘ str_MailTo = rs1(str_MailTo) & «»
str_MailCc = rs1(str_MailCc) & «»
‘str_MailBCc = rs1(str_MailBCc) & «»
‘ str_MailAddressTo = rs1(str_MailAddressTo) & «»
‘str_MailAddressTo1 = str_MailAddressTo
‘For Each fld In rs1.Fields
‘ str_MailAddressTo1 = Replace(str_MailAddressTo1, «[» & fld.Name & «]», rs1(fld.Name))
‘ Next
str_attachmentFile1 = str_attachmentFile
For Each fld In rs1.Fields
str_attachmentFile1 = Replace(str_attachmentFile1, «[» & fld.Name & «]», rs1(fld.Name))
Next
str_Subject1 = str_Subject
For Each fld In rs1.Fields
str_Subject1 = Replace(str_Subject1, «[» & fld.Name & «]», rs1(fld.Name))
Next
str_MailAddressTo1 = str_MailAddressTo
For Each fld In rs1.Fields
str_MailAddressTo1 = Replace(str_MailAddressTo1, «[» & fld.Name & «]», rs1(fld.Name))
Next
str_MailBody1_1 = str_MailBody1
For Each fld In rs1.Fields
str_MailBody1_1 = Replace(str_MailBody1_1, «[» & fld.Name & «]», rs1(fld.Name))
Next
str_MailBody2_1 = str_MailBody2
For Each fld In rs1.Fields
str_MailBody2_1 = Replace(str_MailBody2_1, «[» & fld.Name & «]», rs1(fld.Name))
Next
For Each fld In rs1.Fields
‘for customized signature (MANOJ)
SigString = «C:Documents and Settings» & Environ(«username») & _
«Application DataMicrosoftSignaturesSignature.txt»
‘for customized signature (MANOJ)
If Dir(SigString) <> «» Then
Signature = GetBoiler(SigString)
Else
Signature = «»
End If
Next
End If
‘ rs1.Close
‘ Set rs1 = Nothing
strsq2 = «SELECT » & str_Query_MailBody2 & » FROM [ContactList_Domestic_5284$] where » & str_key & «=» & key_data1(i)
Set rs2 = db2.OpenRecordset(strsq2) ‘added by MANOJ for ContactList_International
If rs2 Is Nothing Then
MsgBox «Error in Fetching MailBody Data!», vbExclamation, ThisWorkbook.Name
Exit Sub
End If
‘To Form the page and header
rs2.MoveFirst
rs2.MoveLast
reccount = rs2.RecordCount
rs2.MoveFirst
str = «»
If (Not rs2.EOF) Then
str_MailTo = rs1(str_MailTo) & «»
str_MailTo1 = str_MailTo
For Each fld In rs2.Fields
str_MailTo1 = Replace(str_MailTo, «[» & fld.Name & «]», rs2(fld.Name))
str_MailTo1 = rs2(str_MailTo) & «»
Next
Else
str_MailTo1 = «» ‘added by MANOJ for ContactList_International uniqueness
End If
str_MailAddressTo = rs1(str_MailAddressTo) & «»
str_MailAddressTo1 = str_MailAddressTo
For Each fld In rs2.Fields
str_MailAddressTo1 = Replace(str_MailAddressTo1, «[» & fld.Name & «]», rs2(fld.Name))
rs2.Close
Set rs2 = Nothing
‘rs1.Close
‘Set rs1 = Nothing
Form_mail str_MailAddressTo1 & str_MailBody1_1 & Signature, str_content, str_MailAddressTo1 & str_MailBody2_1 & Signature, str_attachmentFile1, str_MailTo1, str_MailCc, str_MailFrom, str_MailAddressTo1
rs1.MoveNext
Next i
rs1.Close
Set rs1 = Nothing
close_db2 ‘added by MANOJ for ContactList_International close
close_db1
|
Zyreial 1 / 1 / 0 Регистрация: 24.01.2014 Сообщений: 57 |
||||
|
1 |
||||
|
25.04.2015, 16:26. Показов 4470. Ответов 6 Метки нет (Все метки)
Задание: Формула в прикрепленном изображении Миниатюры
__________________
0 |
|
1 / 1 / 0 Регистрация: 24.01.2014 Сообщений: 57 |
|
|
25.04.2015, 16:27 [ТС] |
2 |
|
Не понимаю, где ошибка. Хотя, я вообще ничего не понимаю
0 |
|
Hugo121 6874 / 2806 / 533 Регистрация: 19.10.2012 Сообщений: 8,550 |
||||
|
25.04.2015, 16:39 |
3 |
|||
|
Ошибка где-то тут:
Там их как минимум 2
0 |
|
1 / 1 / 0 Регистрация: 24.01.2014 Сообщений: 57 |
|
|
25.04.2015, 17:00 [ТС] |
4 |
|
Ошибка где-то тут: он на «i » указывает. Там, где «Next i»
0 |
|
es geht mir gut 11264 / 4746 / 1183 Регистрация: 27.07.2011 Сообщений: 11,437 |
|
|
25.04.2015, 17:02 |
5 |
|
Так у тебя фор = х а некст — i И вторая ошибка x должен быть single или double , иначе шагать будет неправильно
0 |
|
6874 / 2806 / 533 Регистрация: 19.10.2012 Сообщений: 8,550 |
|
|
25.04.2015, 17:03 |
6 |
|
Ну так определитесь какую переменную цикла выбрать.
0 |
|
Заблокирован |
||||
|
25.04.2015, 17:38 |
7 |
|||
|
Попробывал исправить, так.. чтобы было приближенно к заданию ..
i = 1 + 1 это выражение будет давать всегда 2, тоже что и i = 2
k = k + 0.5 также непонятно предназначение этой переменной
1 |
- Remove From My Forums
-
Question
-
Hi,
Software runs ok until a crash takes place in line
‘ End of loop
Next i
. What is this?
—————————
Microsoft Visual Basic
—————————
Compile error:Invalid Next control variable reference
—————————
OK Help
—————————If I press the help button
——————————————————————————
No help available
Not all errors have an associated help topic. This error has the following causes and solutions:
You generated an error for which no Help exists.
Check the Readme file. Help for late-breaking errors is often available through the Readme file.
——————————————————————————
BR,
ob
Answers
-
Hi
Post your code and this should be easy to spot. My guess is you have some nested loops and you have refered to the wrong variable with the next statement.
Regards
ADG
score:3
Accepted answer
Try this
Sub Demo()
Dim srcSht As Worksheet, destSht As Worksheet
Dim lastRow As Long
Dim cel As Range, rng As Range
Set srcSht = ThisWorkbook.Sheets("Sheet1") 'this is your source sheet
Set destSht = ThisWorkbook.Sheets("Sheet2") 'this is your destination sheet
With srcSht
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row 'get last row with data in Column A of srcSht
For Each cel In .Range("A2:A" & lastRow) 'loop through each cell in Column A of srcSht
cel.Copy destSht.Range("R1") 'copy cell in Column A of srcSht to Cell R1 of destSht
cel.Offset(0, 1).Copy destSht.Range("I7") 'copy cell in Column B of srcSht to Cell I7 of destSht
Set rng = Union(destSht.Range("R1"), destSht.Range("I7")) 'union cell R1 and I7
With rng.Font 'format union range
.Name = "Calibri"
.Size = 20
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ThemeColor = xlThemeColorLight1
.TintAndShade = 0
.ThemeFont = xlThemeFontMinor
End With
destSht.Range("I7").Font.Size = 16
'I've not tested save as pdf file part
destSht.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=ThisWorkbook.Path & "" & (cel.Row - 1) & ".pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=True, _
OpenAfterPublish:=False
Next cel
End With
End Sub
Note : I’ve not tested saving file as pdf part.
Related Query
- Compile error invalid Next Control Variable Reference VBA
- Error message: Invalid next control variable reference
- Invalid Next control variable reference ERROR
- «Invalid Next Control Variable Reference» Error in VBA Excel 2003
- VBA for loop with two input variables returning «invalid next control variable reference» error
- Invalid Next Control variable Reference
- «Invalid Next Control Variable reference» Error in excel vba
- VBA compile error if Instr function used with named parameter and return value assigned to variable
- Access VBA Compile error Invalid ParamArray Use
- Avoid Compile Error with a global variable dependant on a reference enabled during script
- excel 2010 vba loop through declared variabels syntax results in Compile error Variable not defined
- Next without For Vba Compile error
- Variable not defined error in image control variable in vba
- VBA AutoCAD Compile Error variable not defined
- VBA Compile Error: «For control variable already in use»
- Trap VBE compile error when running editor under VBA control
- VBA — Why do I get a compile error expected function or variable
- compile error variable not defined VBA
- VBA Invalid or Unqualified Reference Compile
- VBA reference to listbox form control by variable name
- An compile error in VBA after requiring variable declaration
- Added an extra variable to a VBA function — now has compile error stating Expected:=
- VBA Access Compile Error variable not defined
- Invalid Next Control Variable
- VBA Excel — Compile Error — Expected function or variable
- Excel VBA Error: Compile Error Next without For
- Need to correct VBA code. Getting error message.»For Control Variable already in use»
- Excel VBA Code: Compile Error in x64 Version (‘PtrSafe’ attribute required)
- simple vba code gives me run time error 91 object variable or with block not set
- VBA RegExp causes Compile error while vbscript.regexp works
More Query from same tag
- Custom Pathing on Excel Cells
- High and low bytes in VBA
- A function or VBA code to determine the last digit in a number
- How to access a named List Style in MS Word from VBA?
- Search on a form that is filtered with a combobox
- Excel VBA — Macro that runs for entire range of cell
- VBA Break Command bound to a key
- How to get last word in a cell using Excel Formula
- Excel — Deleting images when deleting a row
- Runtime error 438 when copying from one workbook to the other
- Do While ActiveCell <> Range
- Get i’th element of an array read from an Excel range
- Passing a control name as string to the Form Object in VBA
- Sheet name as variable to get last row from function
- What would be the best way to write repetitive code like this?
- Changing bin size of Histogram
- Word VBA — How to insert references of heading number; heading text; list item number and list item page number to comment?
- Using counter within an «—[]» expression in vba
- Setting a global Scripting.Dictionary in Visual Basic for Applications (VBA)
- Submit or bypass form for a Web Query
- How to insert a variable in a countif formula in VBA?
- Hardware Enable/Disable in vb6
- Conditional sum with merged cells using Sumiif()
- Magento CSV import , CSV file with full web address , Download the images
- Microsoft Access: How to do IF in Calculated Field Expression?
- Copy userform to another workbook
- if then else statement makes exactly the same in vba excel
- Populate an Excel table with a collection object
- Handle Alert PopUp Dialog of Macro enabled Excel File using C#
- Copy range of cells to a new location

