代码之家  ›  专栏  ›  技术社区  ›  Ans

在工作簿打开时创建并分配变量,将其传递给工作表更改

  •  1
  • Ans  · 技术社区  · 6 年前

    Workbook_open 创建 Long 打开工作簿时的变量:

    Private Sub Workbook_open()
      MsgBox ("Workbook opened")
    
      Dim i As Long
      i = 68 
    End Sub
    

    i 价值 Worksheet_change 特定工作表的子工作表?

    2 回复  |  直到 6 年前
        1
  •  11
  •   Mathieu Guindon    6 年前

    Dim i 在程序范围内 i 地方的

    通过的想法

    但在这种情况下 很紧,因为事件处理程序的参数是由事件源提供的:您需要将该局部变量“提升”到一个作用域级别。

    以及 级别是 模块范围

    可以 使用 Dim Private 相反。所以 在同一模块中

    Option Explicit
    Private i As Long
    
    Private Sub Workbook_open()
      MsgBox "Workbook opened"
      i = 68 
    End Sub
    

    如果要在该模块之外公开该变量的值,可以公开 为了它:

    Option Explicit
    Private i As Long
    
    Private Sub Workbook_open()
      MsgBox "Workbook opened"
      i = 68 
    End Sub
    
    Public Property Get MyValue() As Long
    'invoked when MyValue is on the right-hand side expression of an assignment,
    'e.g. foo = ThisWorkbook.MyValue
        MyValue = i
    End Property
    

    Sheet1 模块的 Worksheet_Change 处理程序可以 它:

    Private Sub Worksheet_Change(ByVal Target As Range)
        MsgBox ThisWorkbook.MyValue
    End sub
    

    但它不能 global variable ,或暴露 突变子

    Option Explicit
    Private i As Long
    
    Private Sub Workbook_open()
      MsgBox "Workbook opened"
      i = 68 
    End Sub
    
    Public Property Get MyValue() As Long
    'invoked when MyValue is on the right-hand side expression of an assignment,
    'e.g. foo = ThisWorkbook.MyValue
        MyValue = i
    End Property
    
    Public Property Let MyValue(ByVal value As Long)
    'invoked when MyValue is on the left-hand side of an assignment,
    'e.g. ThisWorkbook.MyValue = 42; the 'value' parameter is the result of the RHS expression
        i = value
    End Property
    
        2
  •  2
  •   Subodh Tiwari sktneer    6 年前

    为此,声明 i 作为一个 Public Variable Standard Module 喜欢 Module1 然后您可以访问 在里面 Sheet Change Event 如果是的话 initialized 在期间 Workbook Open Event

    在标准模块上:

    Public i As Long
    

    在此工作簿模块上:

    Private Sub Workbook_open()
      MsgBox ("Workbook opened")
      i = 68
    End Sub