在循環的第二次迭代中,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
謝謝!看起來我在那裏是一個木偶,但是你保存了一天。 – Chuckles