Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subscript out of range Error after renaming sheets

Tags:

excel

vba

I have done a small project, which consists of 5 excel sheet in, code is working fine and I am getting exact result also, but if I rename sheets from sheet1 to some other name I am getting Subscript out of range Error.

What is the reason for this and what needs to be done to overcome this. Please help.

Below is the code

Public  Sub amount_final()

Dim Row1Crnt As Long
Dim Row2Crnt As Long


With Sheets("sheet4")
Row1Last = .Cells(Rows.Count, "B").End(xlUp).Row
End With

Row1Crnt = 2
With Sheets("sheet3")
Row2Last = .Cells(Rows.Count, "B").End(xlUp).Row
End With
like image 519
neobee Avatar asked Mar 29 '12 10:03

neobee


People also ask

How do I remove subscript out of range error?

If we run this code using the F5 key or manually, we will get Run time error '9': “Subscript out of Range.” To fix this issue, we need to assign the length of an array by using the “ReDim” word. This code does not give any errors.

Why does this code generate a subscript out of range error?

This error has the following causes and solutions: You referenced a nonexistent array element. The subscript may be larger or smaller than the range of possible subscripts, or the array may not have dimensions assigned at this point in the application.

Why does my macro say subscript out of range?

"Subscript out of range" indicates that you've tried to access an element from a collection that doesn't exist. Is there a "Sheet1" in your workbook? If not, you'll need to change that to the name of the worksheet you want to protect. Save this answer.

What is Run Time error 9?

"Runtime error 9: Subscript out of range"This error occurs when drilling into a parent unit within the DrillDown Viewer.


1 Answers

There is nothing wrong with the code per se. You will get Subscript out of range error if Excel is not able to find a particular sheet which is quite obvious since you renamed it. For example, if you rename your sheet "Sheet3" to "SheetXYZ" then Excel will not be able to find it.

The only way to avoid these kind of errors is to use CODENAME of the sheets. See Snapshot

enter image description here

Here we have a sheet which has a name "Sample Name before Renaming"

So consider this code

Sheets("Sample Name before Renaming").Range("A1").Value = "Blah Blah"

The same code can be written as

Sheet2.Range("A1").Value = "Blah Blah"

Now no matter how many times you rename the sheet, the above code will always work :)

HTH

Sid

like image 77
Siddharth Rout Avatar answered Nov 15 '22 08:11

Siddharth Rout