VBA - 何时指定 ActiveWorkbook

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

VBA - When to specify ActiveWorkbook

excelvbaexcel-vba

提问by VBAMadeMeDoIt

When writing VBA code, if you know you're going to be operating in the same workbook and on a certain worksheet, should you specify ActiveWorkbookfor the workbook objects in your code there? Example:
ActiveWorkbook.Sheets("Sheet1").Range("$A$1")
vs
Range("$A$1")
Above code assumes you are working off of Sheet1 through local macros(under Sheet1 object in VBA).

在编写 VBA 代码时,如果您知道要在同一个工作簿和某个工作表上进行操作,是否应该ActiveWorkbook在代码中指定工作簿对象?示例:
ActiveWorkbook.Sheets("Sheet1").Range("$A$1")
vs
Range("$A$1")
以上代码假定您通过本地宏(在 VBA 中的 Sheet1 对象下)使用 Sheet1。

回答by Jarom

Better than using ActiveWorkbookin most situations is using WorkBooks("Book1")This is more specific and robust and I believe faster to execute than activating a workbook and then pointing to it when referencing ranges.

ActiveWorkbook在大多数情况下使用更好的是使用WorkBooks("Book1")这更具体和健壮,我相信执行速度比激活工作簿然后在引用范围时指向它要快。

The VBA will default to the last active workbook if you do not designate one when using lines of code like Range("A1")So if you are working in just one workbook it is not necessary since the last active workbook should always be the workbook you want the code to execute in. I typically only designate sheets and ranges when I'm working in a single workbook since it is a little redundant to tell excel to select the active workbook when it already does by default in the absence of a specific workbook designation.

在VBA将默认为最后一个活动工作簿如果使用的像行代码,当你不指定一个Range("A1")所以,如果你只在一个工作簿是不必要的,因为最后一个活动工作簿中应始终是你想要的代码来执行工作簿in. 我通常只在单个工作簿中工作时指定工作表和范围,因为在没有特定工作簿指定的情况下告诉 excel 选择活动工作簿默认情况下已经这样做有点多余。

Just make sure that you will be running the macro from the open workbook that you want the code to execute in.

只需确保您将从要在其中执行代码的打开工作簿运行宏。

Including a workbook designation will never hurt and it will make your code more robust. But if you will only ever have the code execute in a single workbook it is not necessary.

包含工作簿名称永远不会受到伤害,它会使您的代码更加健壮。但是,如果您只在单个工作簿中执行代码,则没有必要。