在编写用于处理电子表格的宏时,我喜欢在模块顶部设置常量,这会腐蚀我必须使用的各种列号。最近,我遇到了一个情况,我需要在两个稍微不同的文件布局上执行完全相同的任务。我的解决方案是将常量转换为变量,并根据要处理的文件调用配置子来设置它们。关于这个解决方案,我唯一不喜欢的是,什么是常量,什么是保护,防止不小心的用户(或开发人员(!))调整代码,现在在一个变量中。
是否有办法使这些配置的值在主子中不可更改?
原始风格:
Const iColUser = 1
Const iColColor = 2
Const iColPet = 3
Sub Main()
iColUser = 3 '<--This line will prevent sub from running.
新款式:
Dim iColUser As Integer
Dim iColColor As Integer
Dim iColPet As Integer
Sub Config()
Select Case SpreadsheetType
Case a
iColUser = 1
iColColor = 2
iColPet = 3
Case b
iColUser = 3
iColColor = 2
iColPet = 1
End Select
End Sub
Sub Main()
iColUser = 2 '<--This line will run, and cause major damage.
发布于 2016-06-05 20:58:53
封装了,,他们。
添加一个类模块,并对这些模块进行抽象。抽象列编号逻辑,为您的列导出Property Get
访问器,然后为“模式”使用Get
和Let
访问器的另一个属性,该属性确定属性返回的值。
Public Enum SpreadsheetType
A
B
End Enum
Private columnMode As SpreadsheetType
Public Property Get Mode() As SpreadsheetType
Mode = columnMode
End Property
Public Property Let Mode(ByVal value As SpreadsheetType)
columnMode = value
End Property
Public Property Get UserColumn() As Long
Select Case Mode
Case A
UserColumn = 1
Case B
UserColumn = 3
End Select
End Property
Public Property Get ColorColumn() As Long
Select Case Mode
Case A
ColorColumn = 2
Case B
ColorColumn = 2
End Select
End Property
Public Property Get PetColumn() As Long
Select Case Mode
Case A
PetColumn = 3
Case B
PetColumn = 1
End Select
End Property
现在要使用它,需要类的一个实例。假设您将其命名为Class1
(天哪,不要这么做!),使用它应该如下所示:
Sub Test()
Dim sheetColumns As New Class1
sheetColumns.Mode = A
Debug.Print sheetColumns.UserColumn 'outputs 1
sheetColumns.Mode = B
Debug.Print sheetColumns.UserColumn 'outputs 3
End Sub
使用此对象的代码只能读取这些值,而不能写入它们--除非您为可变值实现了一个Property Let
访问器。
https://stackoverflow.com/questions/37649555
复制