【问题标题】:Access a variable of a module in another module after running the program which calls that module?在运行调用该模块的程序后访问另一个模块中的模块变量?
【发布时间】:2015-09-19 08:47:15
【问题描述】:

我有一个带有 2 个按钮的 excel 文件,可以访问两个不同的模块。在运行调用该模块的程序后,我们可以访问另一个模块中的模块变量吗?

我的模块看起来像这样

第一个模块..

Public Sub Directory_Path()
Dim Directory As String
    Directory = InputBox("Enter the Directory path that contains folders ""This Quarter"",""Last Quarter"",""Second_Last_Quarter"".")
    If Right(Directory, 1) = "\" Then
    Directory = Left(Directory, Len(Directory) - 1)
    End If
End Sub

我使用 Public Sub Directory_Path() 调用了第二个模块中的第一个模块。我希望将第一个模块中的目录变量用作第二个模块中的变量...

【问题讨论】:

  • 你在问类似this的问题
  • 我不想调用整个模块,只是一个模块中的一个变量
  • 变量是在模块级别还是在子/函数中声明的?
  • 在一个子............
  • 在 Sub 中声明的变量只能在该 Sub 中访问。此外,如果未声明为静态,则变量的生命周期会在 Sub 完成运行后立即结束。您可以将变量移动到模块级别并将其声明为 Public,或者您可以返回变量(通过将 Sub 更改为 Function 或使用 ByRef 参数)

标签: vba excel


【解决方案1】:

在第一个模块中 - 在任何子/函数之外的模块顶部将目录声明为公共。现在此项目中的每个模块都可以使用它:

Public Directory As String

Sub Directory_Path()

    Directory = InputBox("Enter the Directory path that contains folders ""This Quarter"",""Last Quarter"",""Second_Last_Quarter"".")
    If Right(Directory, 1) = "\" Then
    Directory = Left(Directory, Len(Directory) - 1)
    End If

End Sub

在第二个模块中,只要在需要的地方使用名称Directory。示例:

MsgBox "The directory path is " & Directory

【讨论】:

  • 不应该在第二个模块中调用 Directory_Path 来首先设置 Directory 的值吗?如果是这样,你是怎么做到的?
  • 某些东西必须设置Directory_Path 的值,否则在第二个模块中访问它时它将只是一个空字符串。问题提到有两个按钮来访问两个模块,但不清楚每个按钮的用途是什么。在更一般的情况下,我更愿意使用函数来返回所需的值,而不是使用公共变量
猜你喜欢
  • 2016-05-15
  • 2020-12-30
  • 2018-06-08
  • 2015-08-27
  • 2017-04-23
  • 1970-01-01
  • 1970-01-01
  • 2021-02-13
  • 1970-01-01
相关资源
最近更新 更多