Excel User Group
Microsoft Excel blogs, forums, files. Read, ask questions, provide answers.

Class variable default value

Latest post Mon, Jun 30 2008 8:01 AM by lecxe. 3 replies.
  • Wed, Apr 16 2008 4:46 AM

    • lecxe
    • Top 25 Contributor
    • Joined on Wed, Jan 9 2008
    • Gävle, Sweden
    • Posts 15
    • Points 267

    Class variable default value

    Hi

    How am I able to assign a default value to a variable in a class module in VBA? For example in VB.NET I can use this declaration:


    Private i as integer = 5

    to set the variable's default value to 5. I want each new instance of the class to have the property Class1.i = 5

    thank you!

    Filed under: ,
    • Post Points: 37
  • Wed, Apr 16 2008 8:56 AM In reply to

    • Pgmer
    • Top 50 Contributor
    • Joined on Mon, Mar 31 2008
    • Posts 8
    • Points 136

    Re: Class variable default value

    If you have

    Private i as Integer;

    In your class (not in a function), you can use the 'Class_Initialize' function to set the variable.  You would do this like so:

    Private Sub Class_Initialize()
        i = 5
    End Sub

     I let my mind wander ... it never came back!

    Filed under:
    • Post Points: 21
  • Sat, Apr 26 2008 6:57 AM In reply to

    Re: Class variable default value

    When I saw this subject, I thought that you wanted to know how a VBA clas can have a default property, as VB does. I see it isn't, but I will continue that thought anyway.

    Personally, I don't agree with default values, but if you want to do it, here is how:

     

    To make a particular property of a class the default property, e.g. to make the Value property the default, do this

    Export the class module to a text file, open it in NotePad (or some other text editor), and add an attribute to the procedure. e.g.,

    Public Property Get Value() As Long
    Attribute Value.VB_UserMemId = 0
        Value = m_Value
    End Property

    Import the class file back into the project.

    Regards

    Bob

    • Post Points: 5
  • Mon, Jun 30 2008 8:01 AM In reply to

    • lecxe
    • Top 25 Contributor
    • Joined on Wed, Jan 9 2008
    • Gävle, Sweden
    • Posts 15
    • Points 267

    Re: Class variable default value

    Private Sub Class_Initialize()
        i = 5
    End Sub

    This was what I was looking for, thank you!

    • Post Points: 5
Page 1 of 1 (4 items) | RSS
Copyright Excel User Group and the relevant contributors, 2008. All Trade Marks acknowledged. This site is a peer-to-peer site and NOT affiliated in any way to Microsoft Corp. All rights reserved.