"无效的下一个控制变量参考" VBA Excel 2003中出错

时间:2015-12-29 07:02:28

标签: excel vba excel-vba for-loop

基本上,我正在尝试将数据从Excel文件提取到此工作表(Auto_Update Sub),代码如下所述:

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

但是,代码在该行返回错误:Next i(Invalid Next Control Variable Reference)。我仔细检查了For ... Next循环的变量和syntacx,但是,我无法找到任何可能的错误。请帮忙!非常感谢你提前。

1 个答案:

答案 0 :(得分:0)

您永远不会关闭以

开头的循环
For x = 247 To 272 Step 1
        If Trim(new_DPR.Cells(x, 2).Value) = "SD-01PST" Then t = x
        Exit For

在使用next x之前,您需要next i