excel vba:工作表名称作为变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40456960/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
excel vba: sheet name as variable
提问by Dinesh M
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
我正在尝试根据变量选择工作表。我可以使用变量 sname 成功重命名工作表,但无法激活相同的名称
Dim sname as String
sname = Trim(Cells(row, 12).Value)
Sheets("Blank (2)").name = sname
Sheets(sname).Activate
Sheets(sname).Select
回答by Mathieu Guindon
You're saying this works?
你说这行得通?
Sheets("Blank (2)").name = sname
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 Sheetscollection every time.
这个想法是获取对您正在使用的工作表的引用,而不是Sheets每次都不断地从集合中获取对象。
Alternatively:
或者:
Dim target As Worksheet
Set target = ThisWorkbook.Worksheets("Blank (2)")
target.Name = sname
target.Activate
target.Select
Note that the Sheetscollection, 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 Worksheetscollection instead - because the Sheetscollection can contain non-worksheet objects (e.g. charts).
请注意,在Sheets您使用时未限定的集合隐式引用活动工作簿。假设活动工作簿与编写代码的工作簿相同,最好用 限定调用ThisWorkbook,并改用Worksheets集合 - 因为Sheets集合可以包含非工作表对象(例如图表)。
Lastly, I doubt there's any need to .Selectanything here. Read more about avoiding .Selectand .Activatehere.
最后,我怀疑这里是否需要.Select任何东西。阅读更多关于避免.Select和.Activate这里。

