Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Excel - how do use VBA to select by object name instead of sheet name? 1

Status
Not open for further replies.

y2k1981

Programmer
Aug 2, 2002
773
IE
I guess the subject line pretty much says it all!! I'm in the process or writing some macros for somebody. how do I select an worksheet by referencing the object name instead of the sheetname. For example sheet1 is called "Phone", so I have
Code:
with Worksheets("Phone")
But I want to put Sheet1 in the brackets instead, as the user may want to change the sheet name from something other than phone. I've tried
Code:
with Worksheets(Sheet1)
- ie leaving out the " & " and I've tried
Code:
with Object(Sheet1)
and
Code:
with Objects(Sheet1)
but to no avail. how do I do this?
 
You can try using the CodeName property.
Here is a little code that lists all of the sheet names and associated code names:
Code:
Sub ListSheets()
    Dim ws As Worksheet
    For Each ws In ThisWorkbook.Worksheets
        MsgBox ws.Name & vbCrLf & ws.CodeName
   Next ws
End Sub
 
If you want to use the order of the sheets in the workbook then

With sheets(1)

will work with the 1st sheets (ie left most sheet)
etc etc Rgds
Geoff

Si hoc legere scis, nimis eruditionis habes
 
dsi - I don't understand, how can I replace my with Worksheets("Sheetname") with your code?

xlbo - your suggestion is good, but as I won't be the user, I'm afraid that the users may move the sheets about. Isn't there any other alternative?
 
Both worksheet and chart pages have (Name) property, which can be changed by the user in excel window, and Name property, which can be changed only either via Property window or using code as CodeName property.
To refer to the sheet use simply it's codename:
[tt]Sheet1.[/tt]
and select rest from drop-down list.
 
perfect ... thanks combo
and thanks everybody for responding
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top