Reputation: 45
I am trying to use a Type inside a Class Module, but I keep getting several errors. I have tried switching between "Private" and "Public", but to no avail.
Can anyone provide me an example of how to use a Type inside a Class Module?
This is what I am trying:
'Class "clsColor"
Private Type Colors
Red as string
Green as string
Blue as string
End Type
Private Hex as Colors
'_____________________________________________
Private Sub Class_Initialize()
Hex.Red = "FF0000"
Hex.Green = "00FF00"
Hex.Blue = "0000FF"
End Sub
'Regular Module
msgbox clsColor.Hex.Red
What can I do to make this Type work inside the Class Module? Or is it better practice to create an extra Class instead of a Type?
Upvotes: 2
Views: 1213
Reputation: 9948
Brian M Stafford proposing a two-class approach noted: "Type
cannot be used in this case" when
you want to set different colors as object property to .Hex
, e.g. via
MyColor.Hex.Blue
"Can anyone provide me an example of how to use a Type inside a Class Module?"
Instead of a successive object hierarchy, it might make calls more fluent, if one passes the wanted color as ►variant argument to .Hex
only.
In this case you need no related class and can profit from Type
(and Enum
) definitions
allowing to get the wanted result e.g. via (enumerated constant)
MyColor.Hex(Blue) ' or via VBA.ColorConstants: MyColor.Hex(vbBlue)
' or via string input: MyColor.Hex("Blue")
Class Color - Header definitions (Enum
, Type
)
Option Explicit
Enum ColorSynonyms
[_Start] = -1
'equivalents to the 8 VBA.ColorConstants (vbBlack, vbRed..)
Black
Red
Green
Yellow
Blue
Magenta
Cyan
White
'---user defined constants
Brown
Grey
Orange
End Enum
Private Type THexColors
Red As String
Green As String
Blue As String
End Type
Private HexColors As THexColors
Class Color - further code
Private Sub Class_Initialize()
With HexColors
.Blue = "0000FF"
.Green = "00FF00"
.Red = "FF0000"
End With
End Sub
Public Property Get Hex(currColor) As String
Select Case currColor
Case "Red", Red, vbRed
Hex = HexColors.Red
Case "Green", Green, vbGreen
Hex = HexColors.Green
Case "Blue", Blue, vbBlue
Hex = HexColors.Blue
Case Else
Hex = "Undefined!"
End Select
End Property
Example Call
Private Sub Test()
Dim MyColor As Color
Set MyColor = New Color
Debug.Print "Blue", MyColor.Hex(Blue)
'alternatively:
Debug.Print "Blue", MyColor.Hex(vbBlue)
Debug.Print "Blue", MyColor.Hex("Blue")
End Sub
Upvotes: 2
Reputation: 8868
A Type cannot be used in this case. Instead use a Class:
Class Colors
Option Explicit
Public Red As String
Public Green As String
Public Blue As String
Class Color
Option Explicit
Private m_Colors As Colors
Private Sub Class_Initialize()
Set m_Colors = New Colors
m_Colors.Red = "FF0000"
m_Colors.Green = "00FF00"
m_Colors.Blue = "0000FF"
End Sub
Public Property Get Hex() As Colors
Set Hex = m_Colors
End Property
Form
Option Explicit
Private Sub Test()
Dim MyColor As Color
Set MyColor = New Color
Debug.Print MyColor.Hex.Red
End Sub
Upvotes: 1