vba 如何在变量中声明活动工作表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/30466233/
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
How to declare an Active Worksheet in a variable?
提问by unikitty94
I'm trying to keep a variable to the currently open worksheet in VBA. So far I have
我试图在 VBA 中为当前打开的工作表保留一个变量。到目前为止我有
 Dim Active As Worksheet
 Set Active = ActiveWorksheet 
For some reason it gives me an error in the last line, saying Object required. My code opens a new worksheet with the data in the Active sheet, so I need a variable to hold my place in the currently active worksheet. Any idea why this isn't working correctly?
出于某种原因,它在最后一行给了我一个错误,说需要对象。我的代码打开一个包含活动工作表中数据的新工作表,因此我需要一个变量来保存我在当前活动工作表中的位置。知道为什么这不能正常工作吗?
回答by Sobigen
You need to use ActiveSheetinstead of ActiveWorksheet
你需要使用ActiveSheet而不是ActiveWorksheet
回答by iShaymus
I prefer not to use ActiveSheet in VBA because if further down the track you start writing code that uses multiple worksheets it can become confusing when trying to determine which is which. I prefer the following
我不喜欢在 VBA 中使用 ActiveSheet,因为如果您开始编写使用多个工作表的代码,那么在尝试确定哪个是哪个时可能会变得混乱。我更喜欢以下
dim ws as Worksheet
ws = Thisworkbook.Worksheets(1)
OR
ws = Thisworkbook.Worksheets("worksheet name")
The only time I use Activesheet now is when I need some code to work on any worksheet regardless of what it contains, which is very rare. In this case as has been stated above use:
我现在唯一使用 Activesheet 的时候是我需要一些代码来处理任何工作表,而不管它包含什么,这种情况非常罕见。在这种情况下,如上所述使用:
dim ws as Worksheet
ws = Thisworkbook.Activesheet
OR
ws = Activesheet
回答by Lutscha
For me I like to directly speak to the worksheet I want to adress using Sheet("Worksheet").
对我来说,我喜欢使用 Sheet("Worksheet") 直接与我想要寻址的工作表对话。
So if you want to take an information form a particular sheet you can use this:
因此,如果您想从特定工作表中获取信息,您可以使用以下命令:
Dim ExampleWorksheet as Worksheet
Dim Example as Integer
Example = Sheets("ExampleWorksheet").Cells(x,y)
So you get rid of messing around with an active or not active worksheets.
因此,您可以摆脱使用活动或非活动工作表的麻烦。

