Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
639 views
in Technique[技术] by (71.8m points)

excel - Identifying a worksheet other than by its name

A worksheet can be identified by its name such as in this example:

Dim mysheet As Worksheet
Set mysheet = ThisWorkbook.Sheets("My Sheetname")

Now I wonder if a worksheet can be identified other than by its name, for example by some unique id or some property or whatever.

My problem is following:

Referring to the code snippet above: if a user changes the name of the worksheet (e.g. from "My Sheetname" to "Your Sheetname"), the snippet obviously won't work anymore.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is a very good article that explains that it is better to use the SheetID (also called codename) instead of the Sheet Name.

Quoting:

The Codename property is the internal name that Excel uses to identify each sheet. Unlike the Worksheet.Name property, the Codename remains the same regardless of sheet name, or sheet order.

The code name can also be changed so that it is more descriptive:

ThisWorkbook.VBProject.VBComponents("Sheet1").Name = "Revenue_Actuals"

and then

Revenue_Actuals.Range("C2").value = 10

works fine.

Using codenames (such as Sheet1.Range("C1").value) is a good idea, however changing code names at runtime as above is not considered good practice by some developers (see for example, comments on the article of the link above).

Using the sheet index is another way to go, but I personally prefer the code name.

Finally, this article lists many ways that a sheet or workbook can be referenced.

I hope this helps!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...