excel - 在 VBA 中使用全局变量

标签 excel vba

上周刚刚开始使用 VBA,并且正在研究工作表与模块以及定义变量。这是我目前拥有的代码:

表1:

Dim writtenvoe As Boolean
Dim verbalvoe As Boolean
Dim voerequired As Boolean
Dim CA14 As Boolean
Dim CA15 As Boolean
Dim W2s As Boolean
Dim tranapp As Boolean

模块1:

Public Sub ImpDocs()

'Is written voe on file?
If Sheet1.CheckBox6.Value = True Or Sheet1.CheckBox8.Value = True Or Sheet1.CheckBox9.Value = True Or Sheet1.CheckBox10.Value = True Then writtenvoe = True Else writtenvoe = False
If Sheet1.CheckBox6.Value = True Then Sheet1.[O40] = "hello" Else Sheet1.[O40] = ""
If writtenvoe = True Then Sheet1.[O39] = "writtenvoe = true" Else Sheet1.[O39] = "writtenvoe=false"

'Is verbal voe on file?
If Sheet1.CheckBox11.Value = True Then verbalvoe = True

'Is a written VOE required?
If Sheet1.CheckBox16.Value = True Or Sheet1.CheckBox18.Value = True Or Not IsEmpty(Sheet1.[H33]) Then voerequired = True
If voerequired = True Then Sheet1.[J35] = "hello" Else Sheet1.[J35] = ""

'Are tax docs CA14 or CA15?
If Sheet1.CheckBox31.Value = True Or Sheet1.CheckBox7.Value = True Or Sheet1.CheckBox32.Value = True Or Sheet1.[H29].Value > 25 Then CA15 = True Else CA15 = False
If CA15 = False Then CA14 = True Else CA14 = False

'Are W-2's on file?
If Sheet1.CheckBox12.Value = True And Sheet1.CheckBox13.Value = True Then W2s = True

'Are 4506-T's on file?
If Sheet1.CheckBox60.Value = True And Sheet1.CheckBox61.Value = True Then tranapp = True

    'Order Wage transcripts if W-2s and 4506-T not on file
    If W2s = False And tranapp = False And CA14 = True Then Sheet4.fullCA14

End Sub

还有模块 1(第二个子例程):

Public Sub test()

If writtenvoe = True Then Sheet1.[N37] = "Yes" Else Sheet1.[N37] = "No"

End Sub

我注意到,在当前格式中,Sub ImpDocs 运行良好并且变量确定正确,但 Sub test 总是返回 false。但是,如果我将所有代码放入模块 1 中,一切都会按预期工作。似乎只有 Sub 测试受到 Sheet1 与 Module1 中声明变量的影响。真的吗?如果是这样,为什么?

谢谢。

最佳答案

Sheet1 是一个 Worksheet 对象,是的一个实例。因此,即使您将 Sheet1 上的所有内容声明为 Public,如果不首先访问实例,您也将无法访问它们。

Dim 用于声明本地变量。它在模块级别也是合法的,但它相当于使用 Private 来声明它们:使用 Dim 关键字声明的变量不会被公开访问 - 我的建议就是对局部变量使用 Dim ,对模块变量使用 Private/Public

当您在标准模块(而不是类模块)中声明公共(public)变量时,您实际上是在声明全局变量 - 每个变量都可以从项目中的任何位置读取和写入访问。如果这听起来是个好主意,请花时间研究“全局变量的利弊”——无论使用哪种语言,它们通常都会导致灾难。您希望变量仅由特定代码编写,并且希望变量的范围尽可能受到限制。

了解如何将参数传递给您的过程。

您正在发现标准模块和类之间的区别:几乎您周围的一切(ApplicationRangeSheet1 等) ) 是一个对象。对象是某个实例(Excel.ApplicationExcel.RangeExcel.Worksheet 等),并且每个实例封装它自己的状态。

标准模块非常适合宏入口点,但对于封装来说不太好 - 而封装是面向对象编程 (OOP) 的基本支柱之一。

关于excel - 在 VBA 中使用全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46369372/

相关文章:

excel - POI : Unexpected record type org. apache.poi.hssf.record.HyperlinkRecord

excel - Range.Columns 和 Range.EntireColumn 之间有什么区别

excel - 具有该名称的查询已存在

excel - 将 SourceData 转换为 Range

excel - 如何在Excel VBA中编写具有多个条件的OR语句

excel - 我无法在 Excel 中找出带有嵌套 if 的公式

excel - Worksheet.Activate 不会触发 Worksheet_Activate 事件

vba - 在 Excel 中使用 VBA 循环遍历范围

Excel:是否存在检测计算模式变化的事件(自动/手动)

vba - 基于使用 Excel VBA 或公式查找 2 行和 1 列来查找值