VBA User Definded Types

mcs26
mcs26 used Ask the Experts™
on
Hi,

I'm little confused as to why the function below does not work. The error message is, Compile Error: User-defined type is not defined. What's strange is if a turn the function into a sub instead and take out the last line, BenchmarkDates = BMDates
the code works and recognises the user defined type.

Use user defined types a lot in the same module and have no issues?

Thanks for any help,
M

Private Type TypeBMDates
    YTD As Date
    MTD As Date
    TMinus5 As Date
    TMinus1 As Date
End Type

Function BenchmarkDates() As TypeBMDates

Dim BMDates As TypeBMDates

    BMDates.YTD = DateSerial(Year(Now), 1, 0)
    BMDates.YTD = Last_Working_Day(BMDates.YTD)
    
    BMDates.MTD = DateSerial(Year(Now), Month(Now), 0)
    BMDates.MTD = Last_Working_Day(BMDates.MTD)
    
    BMDates.TMinus5 = Last_Working_Day(DateAdd("d", -7, Date))
    
    BMDates.TMinus1 = Last_Working_Day(DateAdd("d", -1, Date))

    BenchmarkDates = BMDates
    
    End Function

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
GrahamSkanRetired
Top Expert 2012

Commented:
The Type should be declared as Public
GrahamSkanRetired
Top Expert 2012

Commented:
I think that there might be a bug (or at least a difference between the documentation and what actually happens)
Commented:
Try

Private Type TypeBMDates
    YTD As Date
    MTD As Date
    TMinus5 As Date
    TMinus1 As Date
End Type

Dim BMDates As TypeBMDates
Dim Last_Working_Day

Private Function BenchmarkDates() As TypeBMDates
    BMDates.YTD = DateSerial(Year(Last_Working_Day), 1, 0)
    BMDates.MTD = DateSerial(Year(Last_Working_Day), Month(Last_Working_Day), 0)
    BMDates.TMinus5 = (DateAdd("d", -7, Last_Working_Day))
    BMDates.TMinus1 = (DateAdd("d", -1, Last_Working_Day))
    BenchmarkDates = BMDates
End Function
                                 
Private Sub Form_Load()
    Last_Working_Day = DateAdd("d", -10, Now)
    BenchmarkDates
    MsgBox BenchmarkDates.YTD
    MsgBox BenchmarkDates.MTD
    MsgBox BenchmarkDates.TMinus5
    MsgBox BenchmarkDates.TMinus1
End Sub
Top Expert 2014

Commented:
What is Last_Working_Day()?

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial