VBA Writing class

Source: Internet
Author: User

First, primary knowledge class

Now, please open your VBE, main menu-Insert-class module.

A class module is inserted, and a class is created. The name of the class module is the name of the class. What you see now, her name is "Class 1", this is VBA according to her sister ranked her, yes, VBA has always been so, you are familiar with this rule, now, in the standard module or other modules to enter the Dim ... As, she has appeared in the Cue box. But I know, there is something you are brooding, "Class 1", too little personality, want to change to their own name it. Very easy, and you change the name of the standard module, open the Properties window, see, the first line is her name, as you wish to modify it.

You may have noticed that under the name there is only one attribute: Instancing, whose value is only two options: Private and PublicNotCreatable. In fact, you can completely ignore this instancing, just as you completely ignore conditional compilation directives, because in VBA we barely use them, and just maintain her default values. At least I think so, but I can't give you enough reason, but only a narrow experience of the individual. Now that we have mentioned it, let me briefly explain:

The Instancing property determines whether the "class" can be used in other projects. We know that the public procedure in a standard module can be saved in a macro workbook or even called directly by another workbook's project, but the code in the class is indivisible, so the overall decision is to allow external use. When the Instancing property is set to private (default), no other project access is allowed. When set to PublicNotCreatable, other projects allow this object to be used only when the object is created by their own project, noting that only the object created in this project is not used to create objects in other projects.

Second, create class properties

We renamed "Class 1" to "MyClass" and created a character-type property called X for it.

1. To create a class property using the public variable

Write the following code in the class module:

Public x$

Yes, it's just that simple, normally, it just needs to be that simple.

2. Creating class properties using Property procedures

Private S $

Public Property Get x () as String

x = S

End Property

Public Property Let X (ByVal C as String)

s = C

End Property

We can save the above default public. But it still seems a little troublesome. Oh, not only two public processes are required, but also an auxiliary private variable s and a parameter C. In the class module, the property process separates the read and write of the properties, and then, when the code in the standard module reads the properties of the object, it will trigger the property get process, or it provides the properties ' read function. , the properties let procedure provides a write property. Thus, the above two processes (of course, there is no order in the module requirements), can only one, or although both have, but is not all public, so that the property provided out is read-only or write-only (hehe, not seen only write ha). Just to provide read-only or write-only properties, the code becomes seven lines from one line?! For such a reason, you will not be convinced that VBA in the class is usually provided to us to use! If it is really read-only, we consciously go to read it only! There are other reasons why we use the property process, and the basic one is that we can use the "process" to do what we want to do. Take a look at:

Public Property Let X (ByVal C as String)

s = Format (c, "0000")

End Property

Here we just make a simple use of a bit, more in the back you will see. In addition, who will guarantee that one day you do not use VB to provide others with the class, this technology is universal. Provide a test code for a standard module to see the class properties we built above, you can try it yourself.

Sub atest ()

Dim MC as New MyClass

mc.x = "123"

Debug.Print mc.x

End Sub

Just as we assign values to ordinary variables and object variables, object variables are assigned using set. For the object attribute, VBA provides the property set in place of the property let used to construct the "normal" attribute. Take a look at the code:

Private TX as Object

Property Get x () as Object

Set x = tx

End Property

Property Set x (ByVal o as Object)

Set tx = O

End Property

Compared with the previous one, come out more a set, really no difference.

Tell you a little secret, you can follow the function to remember the use of property get, according to sub to remember the property let/set.

3. The initial value of the property

We often hope that when an object is established, some of its properties are automatically assigned an initial value, so that the object with the most common attribute values can reduce the duplication of assignments. This needs to be done with the help of a class's build function.

In the Class Module code window, click the small triangle arrow in the "General" box, select "Class", the right declaration box can see two options, "Initialize" and "Terminate", we should not be unfamiliar with them, many objects have these two events, The Initialize event occurs when an object is established, and the Terminate event occurs when the object is disposed. Because classes are static, they are not real objects, so in class modules they are often called build functions and destructors, or build processes and destructors. There is no difference between their understanding and your use of the object. When an object is built, the build function is executed first, and the destructor is executed when the object is freed.

The following establishes the MyClass, the entire test code with the initial value of "0001" for the attribute x:

[Code for class module MyClass]

Option Explicit

Private S $

Public Property Get x () as String

x = S

End Property

Public Property Let X (ByVal C as String)

s = C

End Property

Private Sub Class_Initialize ()

s = "0001"

End Sub

[Code for standard Module 1]

Option Explicit

Sub atest ()

Dim MC as New MyClass

Debug.Print mc.x

End Sub


Iii. Creating a class method

1. The method of building the class is to write the common sub and function in the class module.
2. Sibling-member events of the method

Let's look at a case of universal significance.

[Important Example]

There are 5 CommandButton controls on the form UserForm1 (the name is default CommandButton 1-commandbutton 5) and a TextBox control (named TextBox1). Requires that when each CommandButton control is clicked, its button text (Caption) is written to TextBox1.

If you don't use classes, we need to write 5 identical click event Codes for 5 CommandButton controls respectively. Such as:

Private Sub CommandButton 1_click ()

TextBox1 = CommandButton 1.Caption

End Sub

The following is the code that uses the class's member event method:

' Code for class module Cmds

Option Explicit

Public WithEvents cmd as CommandButton

Private Sub Cmd_click ()

Userform1.textbox1 = cmd. Caption

End Sub

' Form UserForm1 's code

Option Explicit

Dim Co as New Collection

Private Sub userform_initialize ()

Dim i%

Dim Myc as Cmds

For i = 1 to 5

Set Myc = New Cmds

Set myc.cmd = Me.Controls ("CommandButton" & I)

Co. Add Myc

Next I

Set Myc = Nothing

End Sub

The last mention of the friend keyword, although there is little use in VBA, but if one day you want to make an ActiveX part, it may be used. The Friend keyword is required because the private part of the class is not visible outside of the class module, but sometimes it needs to be accessed from outside, and you can use the Friend keyword to make the property and method a friend member. A friend member is a public in this project, but outside of the project, it is still private.

VBA Writing class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.