2016-07-25 107 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。 –

相關問題