本文介绍了如果在"Sheets","ThisWorkbook"和"Modules"中运行VBA代码,会有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在"Sheets"("Sheet1","Sheet2"等),"ThisWorkbook"和"Modules"("Module1"等)中运行VBA代码有什么区别? /p>

换句话说,在哪种情况下应该使用哪个?

解决方案

模块是相似功能和子例程的集合,通常按功能分类.

在模块子例程/函数中,私有:功能和子例程仅在该模块内可用.公开:可以从任何地方直接访问它们. (另一个模块,不同的宏等)将实用程序功能存储在模块中是常见的做法.

Option Private Module,可以将模块本身设为私有,可以添加到任何标准模块的顶部,但不允许在对象模块(如ThisWorkbook或Sheet1等)上使用.


ThisWorkbook是Workbook对象的专用模块.例如, Workbook_Open() Workbook_Close()例程位于此模块中. ( 工作簿对象参考 )


类似地,Sheet1,Sheet2是各个工作表的专用模块.在其中,您需要输入特定于该工作表的函数. Worksheet_Activate Worksheet_Deactivate Workbook_SheetChange 是提供给您的默认事件,以便您可以在各自的专用工作表中处理这些事件模块. ( 工作表对象参考 )

正如@Daniel Cook在评论中所说,虽然ThisWorkbook和WorkSheet的模块不能直接用作模块外部的subName()functionName(),但仍然可以使用ThisWorkbook.subName()ThisWorkbook.functionName()


在VBA中,类模块是最接近OOP的模块.它们具有构造函数,析构函数,并且可以实例化以提供类对象.

What difference does it make if one runs a VBA code in "Sheets" ("Sheet1", "Sheet2", etc.), in "ThisWorkbook", and in "Modules" ("Module1" etc.)?

In other words, which one should be used in which cases?

解决方案

A module is a collection of similar functions and sub-routines, grouped usually in terms of their functionality.

In a module subroutine/function, Private : Functions and Sub-routines are available only within that module.Public : They can be accessed from anywhere, directly. (Another module, different macro etc)It is common practice to store utility functions in modules.

Option Private Module, which makes the module itself private can be added to the top of any standard module, but is not permitted on an object module, like ThisWorkbook, or Sheet1, etc.


ThisWorkbook is a private module of the Workbook Object. For example, Workbook_Open(), Workbook_Close() routine, reside within this module. (Workbook Object Reference)


Similarly, Sheet1, Sheet2 are private modules of the individual sheets. In them, you would put in functions specific to that sheet. Worksheet_Activate, Worksheet_Deactivate, Workbook_SheetChange are default events provided to you, so that you can handle them, within the respective private sheet modules. (Worksheet Object Reference)

As @Daniel Cook said in the comments, while ThisWorkbook and the WorkSheet's modules aren't available for direct use as subName() or functionName() outside the module, it is still possible to call them using ThisWorkbook.subName() or ThisWorkbook.functionName()


A class module is the closest you can get to OOP in VBA. They have constructors, destructors, and can be instantiated to give you class objects.

这篇关于如果在"Sheets","ThisWorkbook"和"Modules"中运行VBA代码,会有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 16:27