|
|
Convert UDT to Class
Problematic UDT usage sample
Project1: Standard EXE containing Form1
Form1: A simple form with a single command button called Command1
Option Explicit
Private Sub Form_Load()
Randomize Timer 'Initialize the random number generator
End Sub
Private Sub Command1_Click()
Dim o As Class1 'Declare the object variable
Dim c As Collection 'Declare the collection variable
Dim i As Integer 'Declare the counter variable
'Here's the first problem. (Strike 1)
'Since the UDT is declared Public in a Standard Module, some believe
'that it should be available to any external project. The problem is
'that no matter how a variable is declared, if it's in a standard
'BAS module, it will be completely Private outside of the project
'it's declared in. That means that the line below won't even
compile.
Dim udt As MyUDT 'Declare the UDT variable
Set o = New Class1 'Instantiate the class
Set c = o.CollectInfo 'Populate the collection (or, at least attempt
to)
For i = 1 To c.Count 'Loop through the collection
udt = c(i) 'Set the UDT variable = collection item
'Of course, since the UDT declaration is invisible to this
'project, the line below won't compile either. (Strike 2)
Debug.Print udt.StringField 'Show the string field
Next
End Sub
Project2: ActiveX DLL containing Module1 and Class
Module1: Standard BAS module
Option Explicit
'I say again, since this is declared Public here some believe that
'it should be available to any external project. The problem is
'that no matter how a variable is declared, if it's in a standard
'BAS module, it will be completely Private outside of the project
'it's declared in.
Public Type MyUDT
StringField As String
FloatField As Double
LongField As Long
End Type
Class1: Class module
Option Explicit
'This function is supposed to return a collection of UDTs
'that have been populated with random data.
Public Function CollectInfo() As Collection
Dim i As Integer
Dim udt As MyUDT
Dim c As Collection
Set c = New Collection 'Instantiate the collection
'This code is fairly straight forward.
'All it does is fill and add 10 copies of a UDT to a collection
For i = 0 To 10
With udt
.FloatField = Rnd * 255
.LongField = Rnd * 255
.StringField = String$(Rnd * 255, Chr$((Rnd * 25) + 65))
End With
'Here we go again with the error message. You can't add a UDT
'to a collection here if declared in a BAS module.
'(Strike 3... YER OUT!)
c.Add udt
Next
'Attempt to display the data. Of course it won't display because
the
'c.Add line above stopped the compiler dead in its tracks.
For i = 1 To c.Count
udt = c(i)
With udt
Debug.Print .FloatField
Debug.Print .LongField
Debug.Print .StringField
End With
Next
Set CollectInfo = c 'Return the collection
End Function
|
|
|