我在Excel中寫了一個VB宏來設置「自動測試」工作表處於活動狀態,並激活與「Date」完全匹配的單元格。然後,我改變這個單元下的每一個日期,以提前4年的年值。我有很多數據集,所以我不希望這些工作簿的格式無法運行。我知道總會有一個「自動測試」工作表,我知道日期列表上方總會有一個「日期」單元格。此代碼適用於大多數數據集,但我一直收到此錯誤,調試點指向lastrow
聲明,但我無法確定問題。提前致謝。接收運行時錯誤'1004'應用程序定義的錯誤或對象定義的錯誤
Sub FourYrsAhead()
' FourYrsAhead Macro
' This macro will forward all of the dates under the "Dates" column in the Autotest sheet forward 4 years.
'Sets variable lastRow as an integer
Dim lastRow As Integer
'Sets theSheetImWorkingOn as a worksheet variable
Dim theSheetImWorkingOn As Worksheet
'Sets theColumnNumberForTheDates as an integer
Dim theColumnNumberForTheDates As Integer
'Activates the Autotest worksheet as the active sheet
Worksheets("Autotest").Activate
'Finds the exact string 'Date' and makes it the active cell
Cells.Find(What:="Date", LookAt:=xlWhole).Activate
'Sets the column number to the current active call value
theColumnNumberForTheDates = ActiveCell.Column
'Sets the sheet that will be worked on
Set theSheetImWorkingOn = Sheets("Autotest")
'Sets the last row variable
lastRow = theSheetImWorkingOn.Cells(1000000, theColumnNumberForTheDates).End(xlUp).Row
'For loop that starts as the active cell row plus 1 and loops down each row
For x = ActiveCell.Row + 1 To lastRow
'Changes the yyyy value in each row ahead 4 years
theSheetImWorkingOn.Cells(x, theColumnNumberForTheDates) = DateAdd("yyyy", 4, theSheetImWorkingOn.Cells(x, theColumnNumberForTheDates))
'Moves to the next row
Next x
End Sub
錯誤1004總是意味着一個變量不存在,或者是不確定的工作簿類型。當您處於調試模式時,將鼠標懸停在變量上。我敢打賭你會發現'theColumnNumberForTheDates'不是一個有效的參考。 (這很可能指向不同的工作表...請參閱此主題:http://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba-macros) – Tim
@Tim當我懸停在theColumnNumberForTheDates,它有一個定義值「4」,這是正確的,因爲'Date'單元格位於第4列 –
@PhilippeGrondier我從線上教程得到了一段代碼,我想數據集將永遠不會達到該數字和代碼似乎與我擁有的大多數數據集一起工作,所以idk爲什麼不能在這裏工作。 –