在VBA类中使用全局常量,类型和函数是一种好习惯吗?

big*_*yes 5 vba

我已经开始使用VBA类了,我一直试图编写我的代码,使每个类都是"独立的",也就是说,它拥有它需要的一切 - 常量,函数等 - 里面.最近,这种方法导致了代码重复,因为我不是在不同模块中调用公共函数,而是将一些代码从"外部世界"(在同一个项目中)复制到一个类中,以保持其"自给自足". .

我正在考虑更改几个类,以便他们能够像其他模块一样从其他模块访问函数,常量,类型等,但是我的一些东西告诉我这可能不是一个好习惯.有人能告诉我这个小小的声音说错了吗?有更好的方法吗?

谢谢.

更新:

对于之前未提供详细信息表示歉意.这是一个示例代码:

'-------------------------------------
'Module 1
'-------------------------------------

Public Const INITIAL_VALUE As String = "Start"
Public Const FINAL_VALUE As String = "End"

'more constants ...

Public Type SheetLoc
   SheetName As String
   SheetRow As Long
   SheetColumn As Long
End Type

'more types ...

'-------------------------------------
'Module 2
'-------------------------------------

Public Function GetLocation(key As String) As SheetLoc

   Dim myLoc As SheetLoc

   'some codes here...
   '
   With myLoc
      .SheetName = someValue
      .SheetColumn = anotherValue
      .SheetRow = stillAnotherValue
   End With

   GetLocation = myLoc

End Function

'more module functions

'-------------------------------------
'Class Module
'-------------------------------------

'some codes...

Public Sub SaveResults()

   Dim currLoc As SheetLoc      '<==== using a type defined outside of the class

   'more declarations ....
   'some codes here ....

   If currentValue = INITIAL_VALUE Then      '<=== referring to external constant 
      currLoc = GetLocation(someKey)         '<=== calling an external function
   ElseIf currentValue = FINAL_VALUE Then    '<=== referring to an external constant 
      currLoc = GetLocation(anotherKey)
   Else
      currLoc = GetLocation(defaultKey)
   End If

   'populate data ...
   'save results ...

End Sub
Run Code Online (Sandbox Code Playgroud)

注意注释中带有"<===="的代码; 该类使用在类之外定义的类型,函数和常量,这使我怀疑这是一个好的做法还是有更好的选择.我想我只是没有完全得到封装概念.

Dic*_*ika 5

我从不将公共常量放在类模块中.所有,我的意思是所有公共变量和常量都在一个名为MGlobals的标准模块中.这有两个好处.首先,你和我都知道在哪里找到它们 - 它们有点危险并且需要找到它们.其次,如果那个模块有多行,我知道我很懒,需要重构.

尝试保持类模块的模块化是一种很好的做法.但不要坚持下去.良好的编程永远不会将选择的模块放入项目中并让它们正常工作.对任何重要项目都有并且应该进行整合.