Excel VBA中的公共变量

时间:2018-12-07 14:04:32

标签: excel vba

如何在“ ThisWorkbook”的声明部分中声明2个“公共”变量,以便在工作表打开后直至关闭之前,所有模块都可以使用它们?尝试使用“公共WarningDate作为日期,ExpirationDate作为日期”,但是只有第一个WarningDate可用。只有1条声明行可用吗?我可以列出多个吗?如果可以,怎么办?

谢谢。

3 个答案:

答案 0 :(得分:1)

您可以通过以下方式在对象模块中使用变量:

工作表模块(例如Sheet1):

Public BigTime As Date, LittleTime As Date

任何模块:

MsgBox Sheet1.BigTime
MsgBox Sheet1.LittleTime

答案 1 :(得分:0)

对象模块

这是不可能的。

您必须区分“正常的” 模块(通过添加模块)和对象模块(ThisWorkbook,Sheet1等)。

如果您在“普通”模块中声明了公共变量,则该变量对于包括 object 模块在内的所有模块的所有过程都是“可见的”,例如:

WarningDate
ExpirationDate

如果您在 object 模块中声明了公共变量,则该变量对于 object 模块的所有过程都是“可见的”,例如:

WarningDate
ExpirationDate

,它将对包括 object 模块的所有其他模块“可见”,但是您必须使用其对象引用来引用它,例如:

ThisWorkbook.WarningDate
ThisWorkbook.ExpirationDate

结论

您正确声明了变量,但是您不知道如何引用它们。如果要访问没有对象引用的公共变量,请添加(或选择)一个模块非对象模块)并在其中声明它们。

可视化

' Code in ThisWorkbook
Option Explicit

Public ThisWorkbookDate As Date

Sub MainThisWorkbook()
  MsgBox ThisWorkbookDate
  MsgBox Module1Date
  MsgBox Sheet1.Sheet1Date
End Sub

' Code in Module1
Option Explicit

Public Module1Date As Date

Sub MainModule1()
  MsgBox ThisWorkbook.ThisWorkbookDate
  MsgBox Module1Date
  MsgBox Sheet1.Sheet1Date
End Sub

' Code in Sheet1
Option Explicit

Public Sheet1Date As Date

Sub MainThis() 'OK
  MsgBox ThisWorkbook.ThisWorkbookDate
  MsgBox Module1Date
  MsgBox Sheet1Date
End Sub

答案 2 :(得分:0)

感谢大家的帮助。我最终只是将日期放置在锁定的第一个工作表的锁定的隐藏单元格中,然后在各种宏和打开的工作簿命令中对其进行引用。这些宏中的每一个都使用这些单元格值重新声明该变量。并非最有效,但它可以工作,我只需要更新3个单元格日期即可更改触发器。我使用的代码是...

Private Sub Workbook_Open()

'Usage Rights Code
        Static WarningDate As Date
        WarningDate = Worksheets("XXX").Cells(1, 1).Value
        Static ExpirationDate As Date
        ExpirationDate = Worksheets("XXX").Cells(2, 1).Value
        Static LockDate As Date
        LockDate = Worksheets("XXX").Cells(3, 1).Value
        '
        If Date >= WarningDate And Date < ExpirationDate Then
            MsgBox "Usage rights for this workbook will expire on " _
                & ExpirationDate & ". After the expiration date, critical " _
                & "calculations will be disabled. Please contact ABC Co." _
                & "to avoid de-activation."
        ElseIf Date >= ExpirationDate And Date < LockDate Then
            MsgBox "Usage rights for this workbook expired on " _
                & ExpirationDate & ". Critical calculations have been " _
                & "disabled. The workbook will be locked on " & LockDate _
                & ". Please contact ABC Co. for re-activation."
        ElseIf Date >= LockDate Then
            MsgBox "Usage rights for this workbook expired on " _
                & ExpirationDate & ". The workbook has been disabled and " _
                & "locked. Please contact ABC Co. for re-activation."
            ThisWorkbook.Close savechanges:=False
        End If

End Sub