• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

Activating Worksheet - Subscript Out of Range

PipBoy808

Member
Apologies for double posting, but I've two different errors within the same macro. I've been trying to activate a particular worksheet just to practice using the following code:

Sub activateSheet()
'activates sheet of specific name

Dim sheetname As String

Worksheets(sheetname).Activate

End Sub

I keep getting the error message 'Runtime error 9: Subscript Out of Range' even though there's definitely a sheet called 'sheetname' within my workbook. Any reason as to why this might be happening?
 
Oh man, it was the damn quotation marks ....

Sub activateSheet()
'activates sheet of specific name

Dim sheetname As String

Worksheets("sheetname").Activate

End Sub

works fine
 
Hi pipboy
While it looks like you've solved it, the problem actually is that you created a VB variable with no content. This:
Code:
Dim sheetname As String
simply tells the VB that you want a variable named "sheetname", it doesn't have a value yet.
When you had the line
Code:
Worksheets(sheetname).Activate
Since the variable had no value yet, the code was trying to activate a sheet called "" (nothing)

Now, you don't have to use a variable. As you discovered, you were able to just plug it in directly with quotation marks. But, if you do want to use a variable, it would be something like
Code:
Dim sheetname As String
sheetname = "Sheet1"
Worksheets(sheetname).Activate
 
Back
Top