0

I am trying to select a sheet based on the variable. I could successfully rename the sheet with variable sname but could not activate the same

Dim sname as String
sname = Trim(Cells(row, 12).Value)
Sheets("Blank (2)").name = sname
Sheets(sname).Activate
Sheets(sname).Select
4
  • works for me. what error do you get? Commented Nov 7, 2016 at 2:47
  • I get the error 'subscript out of range' Commented Nov 7, 2016 at 2:50
  • Why would you need to .Activate and .Select the sheet anyway? Commented Nov 7, 2016 at 3:00
  • subscript out of range in this case would mean the sheet doesn't exist. sure it's right? sure you've got the right workbook open? Commented Nov 7, 2016 at 5:14

1 Answer 1

2

You're saying this works?

Sheets("Blank (2)").name = sname

Then, do this:

With Sheets("Blank (2)")
    .Name = sname
    .Activate
    .Select
End With

The idea is to grab a reference to the worksheet you're working with, instead of constantly fetching the object from the Sheets collection every time.

Alternatively:

Dim target As Worksheet
Set target = ThisWorkbook.Worksheets("Blank (2)")
target.Name = sname
target.Activate
target.Select

Note that the Sheets collection, unqualified as you've used it, implicitly refers to the active workbook. Assuming that active workbook is the same workbook the code is written in, it's best to qualify the call with ThisWorkbook, and to use the Worksheets collection instead - because the Sheets collection can contain non-worksheet objects (e.g. charts).

Lastly, I doubt there's any need to .Select anything here. Read more about avoiding .Select and .Activate here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.