在同一个Excel工作簿中写了很多小的sub()后,我意识到我经常使用相同的部分代码,变量和常量。因此我决定为代码编写funcions(),并声明变量&常量/静态为公共外部函数和子。我对vba声明很新,这并不容易。让我总结一下我想要实现的目标。我已经在工作簿的模块目录下的一个模块中编写了所有函数和子函数。
Option Explicit
Public ToDate As String ' variable I use in many sub and functions
Public MyPath As String ' variable I use in many sub and functions
Public NameOfWorker As Variant ' constant I use in many sub and functions
Public Salary As Double ' constant I use in many sub and functions
NameOfWorker = Cells(14, 19) ' !!! PB : 14 is highlighed with error : incorrect instruction outside a procedure
Salary = Cells(20, 7).Value '!!! same as above
我如何以及在何处声明此类常量/静力学?我应该写一个“特殊”程序来声明所有这些变量和常量吗?我尝试了很多方法宣布它们没有成功。
Public Static NameOfWorker = Cells(14, 19) As String ' not working
''''''
Public Static nameOfWorker As String
NameOfWorker = Cells(14, 19) ' not working
''' etc etc
感谢您的帮助。
编辑:经过更多阅读后,我找到了一种解决方案:
Public Const MY_PATH = "Y:\path\to\directory\"
Public Const WORKERNAME = "14, 19"
不是很糟糕: - )
答案 0 :(得分:2)
您可以创建一个名为DataHelper
的新模块,如下所示:
Private NameOfWorker As String
Private AgeOfWorker As Long
Private SetupComplete As Boolean
Public Function GetNameOfWorker()
If NameOfWorker = "" Then
NameOfWorker = Sheets("SomeSheet").Cells(14, 19)
End If
GetNameOfWorker = NameOfWorker
End Function
Public Function GetAgeOfWorker()
...
End Function
现在在任何其他代码中,您可以检索该值:
Sub SomeMethod()
Cells(1, 1).Value = DataHelper.GetNameOfWorker()
End Sub
......你永远不必担心它是否已被设定。
答案 1 :(得分:1)
好问题!
我会 Dim 模块中所有子元素上方的全局变量,但在某个子元素中的方便位置初始化全局变量。例如:
Public NameOfWorker As String
Public AgeOfWorker As Long
Public SetupComplete As Boolean
Sub MAIN()
If SetupComplete Then
Else
NameOfWorker = Sheets("Sheet1").Range("B9")
AgeOfWorker = Sheets("Sheet1").Range("B10")
SetupComplete = True
MsgBox "Global variable set up complete!"
End If
End Sub