2016-07-25 52 views
0

我在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 
+0

错误1004总是意味着一个变量不存在,或者是不确定的工作簿类型。当您处于调试模式时,将鼠标悬停在变量上。我敢打赌你会发现'theColumnNumberForTheDates'不是一个有效的参考。 (这很可能指向不同的工作表...请参阅此主题:http://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba-macros) – Tim

+0

@Tim当我悬停在theColumnNumberForTheDates,它有一个定义值“4”,这是正确的,因为'Date'单元格位于第4列 –

+0

@PhilippeGrondier我从线上教程得到了一段代码,我想数据集将永远不会达到该数字和代码似乎与我拥有的大多数数据集一起工作,所以idk为什么不能在这里工作。 –

回答

0

根据您运行的是哪个版本的excel,可能超出了excel的行限制。在2003年及以前,工作表限于65536行,因此调用Cells中的第1,000,000行将导致错误。但是,如果您正在运行2007或更高版本,这不应该成为问题。

使用YourSheet.Rows.Count代替1000000将避免造成这个错误,同时还保证所有的数据被覆盖

+0

谢谢,这就是它。我运行的是2016 Excel,但是遇到问题的文件是类型:Microsoft Excel 97-2003。我将不得不将它们重新保存为一个新的excel表单。谢谢! –

+0

@JordanWood或者,只需使用小于100万的值(或许是65535?) – RGA

+0

谢谢,这也起作用。尽管如此,最好将它们更新为.xlsx。 –

相关问题