Invalid next control variable reference ошибка vba

Добрый день уважаемые форумчане. Учусь самостоятельно работать в VBA, параллельно автоматизирую различные несложные рабочие сценарии. При написании последнего макроса столкнулся с ошибкой, которую никак не получается исправить, либо найти её причины. Ошибка наверняка очень глупая, либо я просто нарушил какое-то неизвестное мне фундаментальное правило в написании.К делу. Имеется макрос, который отыскивает на листе "Трафик" в столбце I значения "Ок" или "Внимание". В случае нахождения - копирует некоторые...
 

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.

Помогите найти ошибку (и не сильно ругайте если она окажется глупой).

Спасибо!

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. Показов 4511. Ответов 6

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


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
Option Explicit
Sub proga()
 
Dim x As Integer, y As Integer, s As Integer, k As Integer, i As Integer
 
For x = -1 To 2 Step 0.5
If x <> 0 Then
 
x = InputBox("x=")
 
    y = x + (2 / x ^ 2)
    s = s + y
    k = k + 0.5
    i = 1 + 1
    
    
    Cells(1, 1) = "x = " & x
 
End If
  
Next i
    
End Sub

Задание:
Вычислить значения и сумму значений функции.
Все промежуточные значения суммы и конечный результат вывести на
рабочий лист.

Формула в прикрепленном изображении

Миниатюры

Ошибка: "invalid next control variable reference"
 

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



0



1 / 1 / 0

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

Сообщений: 57

25.04.2015, 16:27

 [ТС]

2

Не понимаю, где ошибка. Хотя, я вообще ничего не понимаю



0



Hugo121

6874 / 2806 / 533

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

Сообщений: 8,552

25.04.2015, 16:39

3

Ошибка где-то тут:

Visual Basic
1
2
3
4
Dim x As Integer
 
For x = -1 To 2 Step 0.5
Next i

Там их как минимум 2



0



1 / 1 / 0

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

Сообщений: 57

25.04.2015, 17:00

 [ТС]

4

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

Ошибка где-то тут:

он на «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,552

25.04.2015, 17:03

6

Ну так определитесь какую переменную цикла выбрать.
Далее т.к. шаг 0,5, то интегер для этой переменной не годится.
Ну а дальше больше… В общем я в саму задачу не вникал, это то что бросилось в глаза.



0



Night Ranger

Заблокирован

25.04.2015, 17:38

7

Попробывал исправить, так.. чтобы было приближенно к заданию ..
и без лишнего вмешательства

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Option Explicit
Sub proga()
 
Dim x#, y#, s#, k#, i#, j&
    On Error Resume Next
    For i = -1 To 2 Step 0.5
        x = InputBox("x=")
        If x <> 0 Then
            y = x + (2 / x ^ 2)
            s = s + y
            k = k + 0.5
    '        i = 1 + 1 ???
            j = j + 1
            Cells(j, 1) = "x = " & x
        End If
    Next
End Sub

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

i = 1 + 1

это выражение будет давать всегда 2, тоже что и i = 2

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

k = k + 0.5

также непонятно предназначение этой переменной



1



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

  • Deleting rows when two blank rows are concurrent
  • update specific cell value when specific cell value is changed
  • Use Exit Code Cleanup When Terminating Code Prematurely
  • VBA Accessing data structure
  • Best way to link two worksheets in excel- vba
  • Filling List in VBA with a loop
  • How to code Excel VBA equivalent of INDIRECT function?
  • How to overwrite the data in database with new data coming from other excel files using VBA?
  • VBA error 1004, can’t find path of folder variable, even though path exists and folder variable holds correct path
  • Inconsistent behavior for Me keyword
  • VBA Copy Whole Column From SQL Recordset
  • How to define file directory in VBA
  • How can I refer to AutoCAD block
  • How to extract URL’s with specific text?
  • Fire an Outlook 2003 macro when the user creates a new blank message
  • VBA Saving (and converting) a Document From .docm to .docx
  • Excel VBA process csv string into array
  • How to change the same title of X-Y axis and formatin in many graphs at once using VBA?
  • How can I implement search within more than one field in text box?
  • Calling Worksheet_SelectionChange (Target) from inside Worksheet_Change (Target)
  • VBA Macros not working first time after download
  • Save Specific single sheet as .csv
  • Select directory in Save As dialog box
  • function for showing unique cells
  • Excel 2010: how to use autocomplete in validation list
  • Add new listrow is giving me a row number 2 on from the last row instead of just 1
  • Update other tables when new row inserted in lead table same worksheet
  • Excel VBA that searches by header name not column
  • Complex If Statements VBA
  • Macro VBA to delete a row only if it doesn’t contain the word «keep» in column BR

Понравилась статья? Поделить с друзьями:
  • Invalid memory access как исправить
  • Invalid mdl range windows 10 ошибка
  • Invalid license number error code 2146893792 an internal error occurred
  • Invalid license data reinstall is required visual studio 2010 как исправить
  • Invalid length nintendo switch ошибка