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

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

 

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.

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

Спасибо!

Search code, repositories, users, issues, pull requests…

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

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 Data\Microsoft\Signatures\Signature.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

Basically, I am trying to pull the data from an Excel file to this worksheet (Auto_Update Sub) and the code is described below:

Sub Auto_Update()
Dim filename As String
Dim r As Integer
Dim i As Double
Dim t As Integer
Dim DPR As Object
Dim new_DPR As Object
Dim well As Object
Dim x As Integer

If IsEmpty(ThisWorkbook.Sheets("SD-28P").Cells(1, 35)) = True Then
ThisWorkbook.Sheets("SD-28P").Cells(1, 35) = Date - 2
End If
Excel.Application.Visible = False
For i = Date - ThisWorkbook.Sheets("SD-28P").Cells(1, 35) To 1 Step -1
    filename = "Z:\DPR\DPR_" + Format(Date - i, "yyyymmdd") + ".xls"
    Set DPR = Excel.Application.Workbooks.Open(filename)
    Set new_DPR = DPR.Worksheets("Daily Production Report")
    For x = 247 To 272 Step 1
        If Trim(new_DPR.Cells(x, 2).Value) = "SD-01PST" Then t = x
        Exit For
    For r = t To t + 35 Step 1
        Set well = ThisWorkbook.Worksheets(Trim(new_DPR.Cells(r, 2).Value))
        f = First_Empty(well, 4)
        If new_DPR.Cells(r, 6).Value = Date - i Then
                new_DPR.Cells(r, 6).Copy
                well.Cells(f, 1).PasteSpecial (xlPasteValues)
                new_DPR.Cells(r, 8).Copy
                well.Cells(f, 3).PasteSpecial (xlPasteValues)
                new_DPR.Cells(r, 10).Copy
                well.Cells(f, 4).PasteSpecial (xlPasteValues)
                new_DPR.Range(new_DPR.Cells(r, 12), new_DPR.Cells(r, 17)).Copy
                well.Range(well.Cells(f, 5), well.Cells(f, 10)).PasteSpecial (xlPasteValues)
                new_DPR.Range(new_DPR.Cells(r, 20), new_DPR.Cells(r, 26)).Copy
                well.Range(well.Cells(f, 11), well.Cells(f, 17)).PasteSpecial (xlPasteValues)
                new_DPR.Range(new_DPR.Cells(r, 28), new_DPR.Cells(r, 30)).Copy
                well.Range(well.Cells(f, 18), well.Cells(f, 20)).PasteSpecial (xlPasteValues)
                well.Range(well.Cells(f - 1, 2), well.Cells(f - 1, 22)).Copy
                well.Range(well.Cells(f, 2), well.Cells(f, 22)).PasteSpecial (xlPasteFormats)
                well.Cells(f - 1, 1).Copy
                well.Cells(f, 1).PasteSpecial (xlPasteFormulasAndNumberFormats)
        End If
    Next r
    Excel.Application.CutCopyMode = False
    DPR.Saved = True
    DPR.Close
    ThisWorkbook.Application.CutCopyMode = False
Next i
ThisWorkbook.Sheets("SD-28P").Cells(1, 35) = Date
ThisWorkbook.Save
Excel.Application.Visible = True
ThisWorkbook.Sheets(4).Activate

But then, the code returns an error at the line: Next i (Invalid Next Control Variable Reference). I double checked the variable and the syntacx of the For … Next loop, however, I couldn’t not find any possible error. Please kindly help! Thank you very much in advance.

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Invalid mdl range windows 10 ошибка
  • Invalid length nintendo switch ошибка
  • Invalid kernel stack address ошибка
  • Invalid input parameters мегафон ошибка
  • Invalid index to scalar variable ошибка

  • Добавить комментарий

    ;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: