Excel 2007 VBA:选择带有变量的工作表

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

Excel 2007 VBA: Selecting Sheet With a Variable

excelexcel-vbavba

提问by broconnor1

I'm trying to reference a sheet based on a variable.

我正在尝试根据变量引用工作表。

From a top level, I have a For loop driven by the variable Num = 1 To 18 The variable "CurrentSN" changes value based on a list of serial numbers on sheet ("SN's").

从顶层来看,我有一个由变量 Num = 1 到 18 驱动的 For 循环变量“CurrentSN”根据工作表上的序列号列表(“SN”)更改值。

Dim Num As Integer 
Dim CurrentSN As String

CurrentSN = Sheets("SN's").Cells(Num, 1).Value

18 pre-existing sheets are in the workbook, each named with one of these serial numbers (18 total). I want to refer to the appropriate sheet for each loop so I used...

工作簿中有 18 个预先存在的工作表,每个工作表都以这些序列号之一命名(总共 18 个)。我想为每个循环参考相应的工作表,所以我使用了...

Sheets(CurrentSN).Range("A1").Select

Unfortunately, it is erroring out on this line. Where am I going wrong here?

不幸的是,它在这条线上出错了。我哪里出错了?

回答by Peter Albert

The problem is that a collection like the Sheetscollection accepts two different kind of inputs:

问题是像集合这样的Sheets集合接受两种不同类型的输入:

  1. A name/key
  2. An index number
  1. 名称/键
  2. 索引号

In your case, you want the key (the serial number), but VBA tries to retrieve the index number, as a number and not a string is provided. Therefore, you need to address your sheet with Sheets(CStr(CurrentSN))!

在您的情况下,您需要密钥(序列号),但 VBA 尝试检索索引号,因为提供的是数字而不是字符串。因此,您需要使用Sheets(CStr(CurrentSN))!

Also, Ross points out, you need to activate the sheet before your select anything in it. Though in 99.999% of the cases, you don't need so use .Select(and therefore .Activate) at all - see http://www.cpearson.com/excel/optimize.htm

此外,Ross 指出,您需要先激活工作表,然后再选择其中的任何内容。尽管在 99.999% 的情况下,您根本不需要使用.Select(因此.Activate) - 请参阅http://www.cpearson.com/excel/optimize.htm

回答by Ross McConeghy

You must activate the sheet before you can select something on it. Use
Sheets(CurrentSN).Activate
before
Sheets(CurrentSN).Range("A1").Select

您必须先激活工作表,然后才能选择其中的内容。使用
Sheets(CurrentSN).Activate

Sheets(CurrentSN).Range("A1").Select