vba 更改工作表名称时如何使宏工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26530466/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 04:58:02  来源:igfitidea点击:

How to get macros to work when sheet name is changed

excelexcel-vbavba

提问by excelSU

How do I make it so my macro will work on a spreadsheet even if someone changes the name of the tab for Sheet1, Sheet2, etc.

即使有人更改了 Sheet1、Sheet2 等的选项卡名称,我如何才能使我的宏可以在电子表格上工作。

For example this snippet from my code:

例如,我的代码中的这个片段:

Set MyWorkbook = Workbooks.Open(DataDialog.SelectedItems(Counter))
Set MySheet = MyWorkbook.Worksheets("Sheet1")

Gets the Run-time error '9':

获取运行时错误“9”:

Subscript out of range

下标超出范围

The issue is I need this macro to able to be used on multiple different workbooks with different named tabs and in a lot of cases tabs will be hidden and what appears to be Sheet1 is really Sheet3. Is there a way to have a macro work on the active sheet alone?

问题是我需要这个宏能够在具有不同命名选项卡的多个不同工作簿上使用,并且在很多情况下选项卡将被隐藏并且看起来是 Sheet1 的实际上是 Sheet3。有没有办法单独在活动工作表上进行宏工作?

回答by Paresh J

Yes, You dont have to hardcode "Sheet1". Instead you can do like following:

是的,您不必对“Sheet1”进行硬编码。相反,您可以执行以下操作:

Method 1: Declare variable

方法一:声明变量

Dim sName as string
sName = Activesheet.Name

And then you can use name in the variable sName instead of hardcoding it.

然后您可以在变量 sName 中使用 name 而不是对其进行硬编码。

Method 2: You can use index of sheets

方法 2:您可以使用工作表索引

sName = Sheets(1).Name

Where 1 indicates index number of sheets in workbook.

其中 1 表示工作簿中工作表的索引号。

So, You can use any of the above two methods to get name of sheet when sheet name changes.

因此,当工作表名称更改时,您可以使用上述两种方法中的任何一种来获取工作表名称。