Initializing a user-defined type

M

mscertified

Is there any quick way to initialize such a type when all the elements in it
are the same e.g.

Public Type typDates
Date1 As Date
Date2 As Date
Date3 As Date
Date4 As Date
Date5 As Date
End Type
 
G

GeoffG

I'm not sure what you have in mind when you say you want to quickly
initialize the elements, but...

When you declare a variable as your type, its elements will be initialised
to zero (as each element is a date type), as demonstrated by the following
example:

Public Type typDates
Date1 As Date
Date2 As Date
Date3 As Date
Date4 As Date
Date5 As Date
End Type

Public Sub TestType()

' Run this code to see zeros in the Immediate window.

Dim usrDates As typDates

Debug.Print usrDates.Date1
Debug.Print usrDates.Date2
Debug.Print usrDates.Date3
Debug.Print usrDates.Date4
Debug.Print usrDates.Date5

End Sub

If you need a specific default value for each element, you could declare a
public or private variable at the module level and call a subroutine that
initialises the elements, as demonstrated by the following example:

Public usrMyDates As typDates

Public Type typDates
Date1 As Date
Date2 As Date
Date3 As Date
Date4 As Date
Date5 As Date
End Type

Public Sub SetDefaultDates()

' Call this subroutine like this:
' Call SetDefaultDates

' FIRST EXAMPLE:

usrMyDates.Date1 = DateSerial(2007, 11, 2)
usrMyDates.Date2 = DateSerial(2007, 11, 3)
usrMyDates.Date3 = DateSerial(2007, 11, 4)
usrMyDates.Date4 = DateSerial(2007, 11, 5)
usrMyDates.Date5 = DateSerial(2007, 11, 6)

Debug.Print usrMyDates.Date1
Debug.Print usrMyDates.Date2
Debug.Print usrMyDates.Date3
Debug.Print usrMyDates.Date4
Debug.Print usrMyDates.Date5


' SECOND EXAMPLE:

usrMyDates.Date1 = Now()
usrMyDates.Date2 = Now()
usrMyDates.Date3 = Now()
usrMyDates.Date4 = Now()
usrMyDates.Date5 = Now()

Debug.Print usrMyDates.Date1
Debug.Print usrMyDates.Date2
Debug.Print usrMyDates.Date3
Debug.Print usrMyDates.Date4
Debug.Print usrMyDates.Date5

End Sub

Geoff
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top