我在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为什么不能在这里工作。 –