2016-11-24 55 views
0

在循環的第二次迭代中,VBA崩潰設置TestRange,這取決於另一個範圍CurrentDataTop,表示「object required ...」。Excel VBA:對象未設置在第二個循環中

我在每個循環的開始處設置了CurrentDataTop,並且第一次迭代遍歷OK。

Option Explicit 

Sub AMystery() 

Dim OutBook As Workbook, MasterWorkbook As Workbook 
Dim CurrentDataTop As Range, CurrentData As Range, TestRange As Range 
Dim Index As Double, i As Double, iTop As Double, iBottom As Double, iColumn As Double 

Set MasterWorkbook = ActiveWorkbook 

'MainLoopStart 
For Index = 1 To 3 

    MasterWorkbook.Sheets.Copy 
    ActiveWorkbook.SaveAs Filename:=MasterWorkbook.Path & "\NewName_" & Index & ".xlsx", FileFormat:=51 
    Set OutBook = Workbooks("NewName_" & Index & ".xlsx") 
    OutBook.Activate 

    ' Set new range starts, within the duplicate book 
    Set CurrentDataTop = OutBook.Worksheets("Sheet3").Range("E6") 

     'Delete some data not required 
      CurrentDataTop.Worksheet.Activate 
      iTop = CurrentDataTop.Row 
      iColumn = CurrentDataTop.Column 
      iBottom = Cells(Rows.Count, CurrentDataTop.Column).End(xlUp).Row 
      For i = iBottom To iTop Step -1 
       If Cells(i, iColumn).Value <> Index Then 
        Rows(i).Delete 
       End If 
      Next i 

     'IT CRASHES HERE ON THE SECOND LOOP, SAYING "OBJECT REQUIRED" 
     Set TestRange = CurrentDataTop.Offset(0, 10) 
     TestRange.Value = "Some text" 

     'Save & close new book 
     OutBook.Save 
     OutBook.Close 

'MainLoopEnd 
Next Index 

End Sub 

回答

1

E6細胞在原始工作簿可能包含的1

的值。因此,在第二次迭代,代碼將刪除包含CurrentDataTop(即細胞E6)的行,因爲細胞不包含a 2.

當您從不存在的單元格轉到Offset時,代碼將崩潰,因爲Offset只能在存在要偏移的對象時執行。

+0

謝謝!看起來我在那裏是一個木偶,但是你保存了一天。 – Chuckles

0

問題是你刪除了所有的CurrentDataTop的單元格。

enter image description here

+0

也感謝這個錄音 - 非常有用:) – Chuckles

+0

謝謝,我很高興你喜歡它。我開始嘗試展示調試技術。 – 2016-11-25 10:47:41