我在Excel 2016,VBA中遇到了問題。爲什麼For ... Next Loop在2次運行後中斷?
請看看代碼:
Private Sub Add_ProjectName()
Dim i As Integer
Dim iRowName As Integer
Dim iColName As Integer
Dim rFind As Range
Dim iFind As Long
Dim ws As Worksheet
Dim lRow As Integer
'Find last row in Master Sheet
Set ws = ThisWorkbook.Worksheets("Master")
ws.Activate
lRow = ws.Cells(ws.Rows.Count, 7).End(xlUp).Row
'Start adding project names per day
With ws
For i = 6 To lRow
Set rFind = .Range(.Cells(5, 14), .Cells(5, 378)) 'Each cell in this range is a date ranging from Feb 1 to Dec 31
rFind.NumberFormat = "mm-dd" 'Change the Format of the Date Range from "dd" to "mm-dd"
iFind = .Cells(i, 4).Value 'The Commencement date of the Project
'Find the Column of the Date that is equal to the Commencement date of the Project on rFind
iColName = rFind.Find(What:=Format(CDate(iFind), "mm-dd"), _
After:=.Range(.Cells(5, 14), .Cells(5, 14)), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=True).Column
'Set the Row of the Commencement date of the Project
iRowName = .Cells(i, 10).Row
'Adding the Project Name
.Cells(iRowName, iColName).Value = .Cells(i, 10).Value
Set rFind = Nothing
Next i
End With
'Change the format of the whole range back to showing the Date only
rFind.NumberFormat = "dd"
End Sub
所以,這個運行良好,前兩個迭代。然後當第三次迭代開始時,我得到的是「運行時錯誤'91' - 對象變量或塊變量未設置」。
調試後,系統說,它是由
iColName = rFind.Find(What:=Format(CDate(iFind), "mm-dd"), _
After:=.Range(.Cells(5, 14), .Cells(5, 14)), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=True).Column
引起我一次又一次的檢查並不能找到「隨着未設定塊」也未設置對象。
有沒有人有任何想法如何解決這個問題?
非常感謝您提前。
你好。
哪種說法是觸發錯誤? – trincot
我必須找到日期列的部分,iColName變量是確切的。我將編輯該問題。感謝您指出了這一點。 –
這意味着'Find'方法找不到匹配項。在搜索之前嘗試'Debug.Print'找到您要查找的值。 –