Property set in vba excel

UserForm and Controls — Properties

———————————————————————-

Contents:

UserForm and Controls

Basic Properties common to the UserForm and most Controls

Other Properties common to the UserForm and most Controls

Specifying Color in Properties Window

Applicability of Properties to UserForm and its Controls — A SnapShot

———————————————————————-

UserForm acts as a container in which you add multiple ActiveX controls, each of which has a specific use and associated properties. By itself, a UserForm will not be of much use unless ActiveX controls are added to it which are the actual user-interactive objects. ActiveX controls can be used with VBA code or without, either directly on worksheets, while some can be used only on VBA UserForms. Using ActiveX Controls on a Worksheet have been illustrated in detail, in the separate section of «Excel VBA: ActiveX Controls, Form Controls & AutoShapes on a Worksheet».

Properties can be viewed in an alphabetical order or category wise by clicking the «Alphabetic» or «Categorized» options in the Properties Window, after selecting the respective Userform or Control. To set/edit, click on that property and make the change in its right column. For help on a Userform or Control property, in the Properties Window select the right column of that property and press F1.

Design-Time, Run-time and Break-time:

The time when an application is being developed in VBE (Visual Basic Environment) is termed as design-time. This is the time when you create a UserForm, add controls and set their properties. Run-time is the time when your code is being executed or the application is running. During this time the developer interacts with the application just like a user and the code cannot be edited then. Break-time is the time when an Application encounters any processing error that prevents the code from continuing or being executed further. Design-time manipulations are not permanent, while run-time are not. For ex, if you add a CheckBox in your code using the Add Method [Set ctrl = Controls.Add(«Forms.CheckBox.1»)], it will appear when the UserForm shows but when you return to VBE, the CheckBox will not be present. Similarly, if you set the Caption of an OptionButton in your code, the new set Caption will appear when the UserForm is displayed but will revert to its original in VBE. The ControlTipText property is set during design-time but is visible on the control during run-time only.

UserForm or Control properties can be set either at design-time or at run-time. Typically, a property which is dynamic is set at run-time and the more static ones at design-time. Name property of a UserForm can be set only at design-time and cannot be set at run-time. Though you can add, name and set properties of controls at run-time, these are mostly done at design-time itself, as these usually remain static while running a procedure. You might face some complications in adding controls and setting properties at run-time, hence only occasionally do you need to set properties at run-time to appropriately cope with a situation.

Setting control properties with vba:

If the code is in a procedure in the Code Module of the UserForm, use the vba syntax:   Controlname.Property = Setting/Value

If the code is in a Standard Module or in the Code Module of a different UserForm, use vba syntax:   UserFormName.Controlname.Property = Setting/Value

Examples of VBA Syntax:

Label1.Font.Name = «Arial»; Label1.ForeColor = RGB(255, 255, 0); OptionButton1.BackColor = 255; CheckBox1.Value = False; CheckBox1.Alignment = fmAlignmentLeft; TextBox1.MultiLine = True; TextBox1.WordWrap = True; TextBox1.ScrollBars = 2; OptionButton1.AutoSize = True; Me.TextBox1.Enabled = False; TextBox1.TextAlign = fmTextAlignLeft; TextBox1.Text = «Hello»; CommandButton1.Left = 50; TextBox1.MaxLength = 5;  Note: Label1, TextBox1, CheckBox1, OptionButton1 & CommandButton1 are the Control names.

_______________________________________________________________________________

Basic Properties common to the UserForm and most Controls

Name Property

Use the Name property to specify a name for a control or to specify the font name (used in the text portion of a control). Name property of a UserForm can be set only at design-time and cannot be set at run-time. Name property for controls can be set either at design-time or at run-time, BUT if a control is added at design-time, its name cannot be changed at run-time. Typically, the default name of the first CheckBox created is CheckBox1, the default name of the second CheckBox will be CheckBox2, and so on, and similalry for other controls too. The default name of the first Userform you have created will be «UserForm1» (Image 1).

By clicking on «Name» in the Properties Window, you can edit the name. The name should begin with a letter, can have any combination of letters, numbers or underscores, cannot have spaces or symbols and can have a maximum length of 40 characters. It might be a good idea to have a 3-letter prefix in lower case, for each name, to identify and associate with its respective control. The characters following the prefix can start with a capital, for easier readibility. Typically, prefix used for different controls are: frm for UserForm; lbl for Label; txt for TextBox; cmb for ComboBox; lst for ListBox; chk for CheckBox; opt for OptionButton; fra for Frame; cmd for CommandButton; tbs for TabStrip; rfe for RefEdit; and so on.

Syntax for Font:  Font.Name = String

Syntax for all other controls and objects:  object.Name = String

The Name Property is applicable to the UserForm and to all controls.

—————————————————————————————————————

Caption Property

Caption is the text which describes and identifies a UserForm or Control. Typically, the default name and Caption of the first CheckBox created at design-time is CheckBox1, the default name and Caption of the second CheckBox will be CheckBox2, …; default name and caption of the first OptionButton is OptionButton1, …; default name and caption of the first CommandButton is CommandButton, …; and so on. The default caption of the first Userform you have created will be «UserForm1» (Image 1). By clicking on Caption in the Properties Window, you can edit the same, in its right column. The Caption will display in the header of the Userform; in re of Label, CommandButton & ToggleButton controls, Caption is the text which appears on the control; in re. of Tab and Page objects Caption is the text that appears on the tab; in re. of CheckBox & OptionButton Caption appears to the side (right or left, as determined by its Alignment property) of the control; in re. of a Frame control Caption appears on the top-left border of the control. Setting the AutoSize property to True (in a control which has both Caption & AutoSize properties), automatically adjusts the control to display the entire caption. Caption can be set in the Properties window or with vba code. Syntax:  object.Caption = String.

Caption property is applicable to the UserForm and controls Label, CheckBox, OptionButton, ToggleButton, Frame, CommandButton, Tab (Tabstrip) and Page (MultiPage).

————————————————————————————————————- 

Size and Position of a Control

Height, Width Properties:

Sets the the height or width, measured in points. You can manually enter the Height and Width in the Properties Window, or when you size a control, the Height and Width properties get updated automatically. For these properties, VBA only accepts values which are greater than or equal to zero. These properties can be set in the Properties window or with vba code. Syntax:  object.Height = Numberobject.Width = Number. You can also resize a control with a mouse in the following manner: select the control -> the  mouse pointer will change to a two-headed arrow when positioned over the control’s handles (adjustment handles) which are in the middle or corner of its side borders -> adjust the horizontal or vertical size by using the appropriate side handles and to change both the horizontal & vertical size simultaneously use the corner handle -> click and drag handle to the required size and then release mouse button.

The Height and Width Properties are applicable to the UserForm and to all controls.

Left, Top Properties:

Left Property sets the distance between the left edge of the control and the left edge of the form that contains it. Top Property sets the distance between the top edge of the control and the top edge of the form that contains it. For a UserForm, the distance set is between the form and the left or top edge of the window that contains it. For both Left and Top properties, distance is set in pixels. You can manually enter the Left and Top properties in the Properties Window or when you move or size a control, the Left and Top properties get updated automatically. If the value of the Left or Top properties is set to zero, the control will appear at the left edge or top edge of the form that contains it, and specifying a value of less than zero in either of these properties will chop a portion of the control which will not remain visible on the form. These properties can be set in the Properties window or with vba code. Syntax:  object.Left = Numberobject.Top = Number. You can also move a control with a mouse in the following manner: select the control -> the  mouse pointer will change to a four-headed arrow when positioned over the control’s border (avoiding the handles used to resize) -> click and drag the control to the required position and then release mouse button.

The Left and Top Properties are applicable to the UserForm and to all controls.

——————————————————————————————————————— 

Value Property

Determines the selection status of a control or specifies the control’s content. With respect to the controls CheckBox, OptionButton and ToggleButton: an Integer value of -1 means True and indicates that the control is selected; 0 value means False and indicates that the control is cleared; and the Null value indicates that the control is neither selected nor cleared, and will appear shaded in this case. For the controls ScrollBar and SpinButton, it indicates their current value, which is an integer between maximum and minimum values specified in the Max and Min properties. For the controls ComboBox and ListBox (value cannot be used with a multi-select ListBox), it is the value in the BoundColumn of the currently selected row (BoundColumn property specifies the column from which value is to be stored in a multicolumn ComboBox or ListBox, when a row is selected by the user). For a CommandButton, it is a Boolean value which indicates whether the control has been chosen — default setting is False and setting it to True (can be done only with vba code) will invoke the button’s Click event. For a MultiPage, the Value property is set (can be done only with vba code) with an Integer which indicates the current (active) page, and pages are numbered starting from zero (0) which is the first page so that the maximum value is one less than the number of pages. For a TextBox, it refers to the text in the text box. Value property can be set in the Properties window (except for CommandButton and MultiPage controls) or with vba code. Syntax:  object.Value = Variant.

The Value property is applicable to all controls except Label, Frame and Image.

____________________________________________________________________________

Other Properties common to the UserForm and most Controls

These properties can be set in the Properties window or with vba code, unless specified otherwise.

Accelerator Property:

Sets the key to access a control — it is referred to as the accelerator key or access key. This key is a single character, pressed in combination with and after the Alt key. It is used as a short-cut and gives focus to a control and initiates the Click event. In case multiple characters are entered as its value, the first character becomes the value of Accelerator. To click the ‘Enter’ command button in a form, the accelerator key can be set as letter «E» and used by pressing Alt+E. In case the accelerator is set for a Label, then the control which follows Label next in the tab order receives focus (but not initiation of the Click event) instead of the Label itself. Note: The character used as the value of accelerator is key-sensitive, meaning that setting the accelerator key as letter P is the same as letter p or the character + is the same as = because they are entered by pressing the same key.

Accelerator property is applicable to the controls Label, CheckBox, OptionButton, ToggleButton, CommandButton and MultiPage. 

———————————————————————————————————— 

Alignment Property:

Specifies how a caption will appear relative to the control. There are 2 settings: (i) fmAlignmentLeft (value 0) — caption appears to the left of the control; and (ii) fmAlignmentRight (value 1) — this is the default setting wherein the caption appears to the right of the control. Note 1: Though ToggleButton has Alignment as one of its properties, it is disabled and Alignment cannot be specified for the ToggleButton. Note 2: The caption text is always left-aligned.

Alignment property is applicable to the controls CheckBox, OptionButton and ToggleButton.

———————————————————————————————————— 

AutoSize Property:

A Boolean value (True/False) which specifies if or not the control resizes automatically for its entire contents to be displayed. Setting AutoSize to TRUE automatically resizes the control while setting AutoSize to FALSE (Default option) keeps the size of the control constant wherein content exceeding the control’s area get cut. For the controls TextBox and ComboBox, AutoSize applies to displayed text; for the Image control, AutoSize applies to the displayed image; while for other controls AutoSize applies to the caption. Settings for TextBox: (i) if the TextBox is single-line, AutoSize resizes width of TextBox to the length of the text; (ii) if the TextBox is MultiLine with no text, AutoSize resizes width to display single letter (of widest width of that font size) and resizes height to display the entire text; and (iii) if the TextBox is MultiLine with text present, AutoSize does not change the width of the TextBox and resizes height to display the entire text.

AutoSize property is applicable to the controls Label, TextBox, ComboBox, CheckBox, OptionButton, ToggleButton, CommandButton, Image and RefEdit.

———————————————————————————————————— 

BackColor Property:

Sets the background color for UserForm and controls. The BackStyle property (in re of controls) should be set to fmBackStyleOpaque for the BackColor to have any effect.

BackColor Property applies to all controls (for MultiPage the property can be set only with vba code) and UserForm.

——————————————————————————————————— 

BackStyle Property:

Determines whether the background of Controls will be Opaque or Transparent. Sets the background style for an object. It has two settings: (i) fmBackStyleTransparent (value 0) for transparent background, wherein everything behind the control on a form is visible; (ii) fmBackStyleOpaque (value 1) for opaque background, wherein nothing is visible behind the control on a form, and this is also the default. The BackStyle property (for controls) should be set to fmBackStyleOpaque for the BackColor to have any effect.

BackStyle is applicable to the controls Label, TextBox, ComboBox, CheckBox, OptionButton, ToggleButton, CommandButton, Image and RefEdit.

————————————————————————————————————— 

BorderColor Property:

Sets the border color for UserForm and Controls. Unless the BorderStyle Property sets a border (ie. it should be a non-zero value, which means other than fmBorderStyleNone), this property will have no effect. BorderStyle defines the border colors using the BorderColor Property while the SpecialEffect property exclusively uses system colors (which are part of the Control Panel for Windows OS) to define its border colors.

BorderColor is applicable to UserForm and the controls Label, TextBox, ComboBox, ListBox, Frame, Image and RefEdit.

————————————————————————————————————— 

BorderStyle Property:

Specifies the type of border for an object (control or a form). It has two settings: (i) fmBorderStyleNone (value 0) for no border; (ii) fmBorderStyleSingle (value 1) for a single-line border. UserForm, Label, TextBox, ComboBox, ListBox and Frame have the default value of 0 whereas the default value for an Image is 1. BorderStyle defines its border colors using the BorderColor Property. Note: You cannot simultaneously use both the BorderStyle and SpecialEffect properties to specify the border for a control — specifying a non-zero property for either one will automatically set the other property to zero. And, if the SpecialEffect property for a Frame is set to zero (ie. Flat), the BorderStyle property is ignored.

BorderStyle is applicable to UserForm and the controls Label, TextBox, ComboBox, ListBox, Frame, Image and RefEdit.

————————————————————————————————————- 

ControlSource Property:

Mentions a cell or field (viz. worksheet range in Excel) which is used to set or store the Value property of a control. Changing the value of the control will automatically update the linked cell and a change in the linked cell will update the value of the control. Where A1 is entered in a ControlSource property of a CheckBox, and if cell A1 in ActiveSheet contains TRUE, the CheckBox will appear selected on activating the form and if you deselect the CheckBox, cell A1 will change to FALSE. In a ListBox where the ControlSource mentions Sheet3!D2, the value in the BoundColumn of the selected row will get stored in cell D2, Sheet3. In a TextBox where the ControlSource mentions Sheet3!F2, the text or value in the TextBox will get stored in the worksheet cell Sheet3!F2 and if the cell Sheet3!F2 contains any text, this will appear in the TextBox on activation of UserForm. The default value is an empty string which indicates that no ControlSource Property has been set. Note: To set ControlSource property in Properties window, enter without inverted commas: =Sheet3!F2, and to set with vba code: .ControlSource = «=Sheet3!F2» or .ControlSource = «Sheet3!F2».

ControlSource property is applicable to the controls TextBox, ComboBox, ListBox, CheckBox, OptionButton, ToggleButton, ScrollBar and SpinButton.

———————————————————————————————————— 

ControlTipText Property:

Specifies the text displayed when the user holds the mouse over a control. It is useful in giving tips or clarifications to the user on using the control. The default value is an empty string which indicates that no text will be displayed.

ControlTipText Property is applicable to all controls.

———————————————————————————————————— 

Enabled Property:

A Boolean value (True/False) which specifies whether the control can be accessed through a vba code and can respond to user-generated events (ie. the user can interact with the control by using mouse, keystrokes, accelerators, or hotkeys). Default value is True, which indicates that the control can be accessed whereas a False value indicates that the user cannot interact with the control. The control is usually accessible through a code even in the case the value is set to False. If Enabled is set to False, the control appears dimmed (except for Image). If Enabled is set to False for a UserForm or a Frame, all controls they contain also get disabled. Enabled Property of a TextBox is particularly useful where you do not want to allow the user to type directly into the TextBox but should be filled only per the user-selected option, say from a ListBox.

Enabled Property applies to all controls and UserForm.

———————————————————————————————————- 

Locked Property:

A Boolean value (True/False) which specifies whether the control is editable or not. True value indicates uneditable, while the default value is False wherein the control can be edited.

Locked property is applicable to the controls TextBox, ComboBox, ListBox, CheckBox, OptionButton, ToggleButton, CommandButton and RefEdit.

Using the Enabled and Locked Properties in conjunction:

1. Enabled is True and Locked is False: the control responds to user-generated events and appears normally; data can be copied and edited in the control.

2. Enabled is True and Locked is True: the control responds to user-generated events and appears normally; data can be copied but not edited in the control.

3. Enabled is False (irrespective of Locked value): the control cannot respond to user-generated events and also appears dimmed; data can neither be copied nor edited in the control.

———————————————————————————————————— 

Font Object:

Determines the type of font used in a control or form. You can specify the font name, set the font style (Regular, Italic, Bold, …), underline or strikeout text, and adjust the font size. For the controls TextBox, ComboBox and ListBox, the font of displayed text is set, while for other controls the caption font is set. Note: Setting Font of a UserForm will automatically set the Font of all controls if entered post the UserForm setting but will not change the Font of these controls if they were already present for which you will need to reset Font of each individual control separately. Font property for a MultiPage control can be used only with vba code.

Font applies to UserForm and all controls except ScrollBar, SpinButton and Image.

—————————————————————————————————— 

ForeColor Property:

Specifies the foreground color ie. color of displayed text. In respect of Font controls, ForeColor determines the text color; in a Frame, ForeColor determines its caption color; in a ScrollBar or SpinButton, ForeColor determines the color of the arrows. Note: Setting ForeColor of a UserForm will automatically set the ForeColor of controls Label, CheckBox, OptionButton, Frame, MultiPage and TabStrip if entered post the UserForm setting and but will not change the ForeColor of these controls if they were already present for which you will need to reset ForeColor of each individual control separately. ForeColor property for a MultiPage control can be used only with vba code.

ForeColor Property applies to UserForm and all controls except Image.

—————————————————————————————————— 

MouseIcon Property:

Assigns an image to a control which gets displayed when the user moves the mouse across that control. Image is assigned by specifying the path and filename of the file it is in. To use the MouseIcon property it is required that the MousePointer property is set to fmMousePointerCustom (value 99).

MouseIcon property is applicable to UserForm and all controls, except MultiPage.

——————————————————————————————————- 

MousePointer Property:

Specifies what type of mouse pointer will be visible when the user moves the mouse over a control. There are 15 settings: (i) fmMousePointerDefault (value 0) — standard pointer, and default value; (ii) fmMousePointerArrow (value 1) — arrow; (iii) fmMousePointerCross (value 2) — Cross-hair pointer; (iv) fmMousePointerIBeam (value 3) — I-Beam; (v) fmMousePointerSizeNESW (value 6) — two-headed arrow pointing northeast and southwest; (vi) fmMousePointerSizeNS (value 7) — two-headed arrow pointing north and south; (vii) fmMousePointerSizeNWSE (value 8) — two-headed arrow pointing northwest and southeast; (viii) fmMousePointerSizeWE (value 9) — two-headed arrow pointing west and east; (ix) fmMousePointerUpArrow (value 10) — up arrow; (x) fmMousePointerHourglass (value 11) — hourglass; (xi) fmMousePointerNoDrop (value 12) — circle with a diagonal line, appearing as a «Not» symbol indicating an invalid control; (xii) fmMousePointerAppStarting (value 13) — arrow and hourglass; (xiii) fmMousePointerHelp (value 14) — arrow and question mark; (xiv) fmMousePointerSizeAll (value 15) — four-headed arrow, pointing north, south, east, and west; and (xv) fmMousePointerCustom (value 99) — image specified by the MouseIcon property.

MousePointer property is applicable to UserForm and all controls, except MultiPage.

——————————————————————————————————- 

Picture Property:

Specifies the picture to be displayed on a control. Picture is assigned by specifying the path and filename of the file it is in. To remove the picture, press DELETE on the value of the property (pressing BACKSPACE will not remove). For controls with captions, you can specify the location of the picture by using the PicturePosition property. For other controls and UserForm, use PictureAlignment Property to specify the location (identifies the control corner to display or at the center) of the picture and use PictureSizeMode Property to specify how (size, scale, strech or enlarge mode) to display the picture.

Picture property is applicable to UserForm and the controls Label, CheckBox, OptionButton, ToggleButton, Frame, CommandButton, MultiPage and Image.

—————————————————————————————————— 

PicturePosition Property:

Specifies where the picture appears in the control vis-a-vis its caption. The alignment of the picture with its caption is determined by this property. There are 13 settings in a format where the string fmPicturePosition is followed by the location of the picture relative to its caption and next is the alignment of the caption relative to the picture, viz. fmPicturePositionLeftTop — the picture appears to the left of the caption and the caption is aligned with the top of the picture; and so on. The last setting is fmPicturePositionCenter — both the picture and caption are centered in the control and the caption is on top of the picture. Default is fmPicturePositionAboveCenter (value 7) — the picture appears above the caption and the caption is centered below the picture. In the absence of a caption, the picture’s location is relative to the center of the control. If no picture is specified to be displayed, the PicturePosition property will have no effect.

PicturePosition property is applicable to the controls Label, CheckBox, OptionButton, ToggleButton and CommandButton.

——————————————————————————————————

SpecialEffect Property:

Determines how the control visually appears. For a CheckBox, OptionButton, or ToggleButton, the two settings are: (i) fmButtonEffectFlat (value 0); and (ii) fmButtonEffectSunken (value 2) — Default for CheckBox and OptionButton. For other applicable controls the five settings are: (i) fmSpecialEffectFlat (value 0) — Default for UserForm and the controls Image and Label; (ii) fmSpecialEffectRaised (value 1); (iii) fmSpecialEffectSunken (value 2) — Default for controls TextBox, ComboBox and ListBox; (iv) fmSpecialEffectEtched (value 3) — Default for Frame; and (v) fmSpecialEffectBump (value 6). The visual appearance of each setting is self-explanatory viz. visual effect can be Flat, Raised, Sunken, Etched and Bump. Note 1: Though ToggleButton has SpecialEffect as one of its properties, it is disabled and SpecialEffect cannot be specified for the ToggleButton. Note 2: You cannot simultaneously use both the BorderStyle and SpecialEffect properties to specify the border for a control — specifying a non-zero property for either one will automatically set the other property to zero. And, if the SpecialEffect property for a Frame is set to zero (ie. Flat), the BorderStyle property is ignored. Note 3: SpecialEffect property exclusively uses system colors (which are part of the Control Panel for Windows OS) to define its border colors.

SpecialEffect property is applicable to UserForm and the controls Label, TextBox, ComboBox, ListBox, CheckBox, OptionButton, ToggleButton, Frame, Image and RefEdit.

——————————————————————————————————

TabIndex Property:

TabIndex is the position of the control in a UserForm’s tab order (when the user presses the Tab key). The Index value is expressed as an Integer, with 0 being the first position in the tab order and the highest possible Index value will be one less than the number of controls in the form, to which the TabIndex property is applicable. Entering an Index value less than zero will give an error, a value greater than the highest possible will reset it to the highest value, and each control will have a unique Index value. TabIndex property for a MultiPage control can be used only with vba code.

TabIndex is applicable to all controls except Image.

——————————————————————————————————

TabStop Property:

A Boolean value (True/False) which specifies whether the control can be selected with the tab key. The True value is the default, and sets the control as a tab stop. The False value ignores the control during user tabs but its position in the tab order (as specified in the TabIndex property) remains intact. TabStop property for a MultiPage control can be used only with vba code.

TabStop is applicable to all controls except Label and Image.

——————————————————————————————————-

Visible Property:

A Boolean value (True/False) which is set to make a control visible or hidden. Default value is True, wherein control is visible. This property is particularly useful wherein on satisfaction of a condition you can activate a hidden control which otherwise you might not want to appear in the UserForm viz. show or hide a message dependent on total marks received in a test.

Visible Property applies to all controls.

——————————————————————————————————-

WordWrap Property:

A Boolean value (True/False) which specifies whether the text of a control will wrap to the next line. Default value is True, wherein the text wraps. If MultiLine property of a control is set to False, WordWrap is ignored (in controls which support both these properties viz. TextBox).

WordWrap property is applicable to the controls Label, TextBox, CheckBox, OptionButton, ToggleButton, CommandButton and RefEdit.

____________________________________________________________________

Specifying Color in Properties Window

To enter or change color, in the property’s right column (in Properties Window) click the «Palette» tab and select a new color, or select a predefined color from the «System» tab. It can also be entered as a Long Integer which represents a valid color (this is the decimal format). Alternatively, the color can be entered in hexadecimal notation. The Properties Window displays values in Hexadecimal format, even if the color is entered in decimal format.

Long Integer as Color: Excel color can be represented as a Long Integer, the integer value being derived from the vba RGB function viz. «RGB(Red, Green, Blue)». In the RGB function, the value of each color component of Red, Green & Blue is in the range of 0 to 255. A Long Integer can be derived from the RGB function as shown below:

RGB Function Deriving Integer Value Long Integer Web/HTML Hexa-decimal (RRG GBB) VBA Hexa-decimal (BBG GRR) Color
RGB(1,0 ,0) =1*1+ 0*256+ 0*65536 1 010000 000001 Black (vari-ation)
RGB(0,1 ,0) =0*1+ 1*256+ 0*65536 256 000100 000100 Black (vari-ation)
RGB(0,0 ,1)  =0*1+ 0*256+ 1*65536  65536 000001  010000  Black (vari-ation) 
RGB(255, 0,0)  =255*1+ 0*256 + 0*65536  255 FF0000  0000FF  Red 
RGB(0, 255,0)  =0*1+ 255*256 + 0*65536  65280 00FF00  00FF00  Green 
RGB(255, 255, 255) =255*1+ 255*256+ 255* 65536  16777215 FFFFFF  FFFFFF  White 
RGB(0,0 ,0)  =0*1+ 0*256 + 0*65536  0 000000  000000  Black 
RGB(255, 255,0)  =255*1+ 255*256 + 0*65536  65535 FFFF00  00FFFF  Yellow 
RGB(255, 0,255)  =255*1+ 0*256 + 255* 65536  16711935 FF00FF  FF00FF  Magenta 
RGB(0,0, 255)  =0*1+ 0*256+ 255* 65536  16711680 0000FF  FF0000  Blue 
RGB(10, 255,255)  =10*1+ 255*256 + 2255* 65536  16776970 0AFFFF  FFFF0A  Aqua (vari-ation) 

Hexadecimal notation for Color:

In hexadecimal format numbers are expressed in base-16 notation. There are 16 hexadecimal digits. The first 10 are the same as decimal digits viz. 0 to 9, and then the six letters A to F in place of decimals 10 to 15. Hence, 16 different values can be represented by a single hexadecimal digit whereas these would be 10 for a decimal digit, making it more compact because values can be represented in fewer digits. Colors are derived from 3 color components of Red, Green & Blue and each component can take a value from 0 to 255 and the corresponding hexadecimal representation is from 00 to FF. FF is the largest hex number, equating to the decimal value of 255. In hexadecimal, color is represented by six characters. In web and HTML programming, hex notation is in the format of RRGGBB (coded as #RRGGBB viz. RRGGBB prefixed with #), wherein the first two characters represent Red, the next two represent Green and the last two represent Blue viz. RRGGBB. The red color represented by RGB function of RGB(255,0,0) equates to integer value of 255 and to hexadecimal notation of FF for the red color and 00 for green and 00 for blue ie. «FF0000». New colors can be derived by mixing the basic 3 color values viz. get yellow from mixing red and green (255,255,0) which equates to integer value 65535 and to hexadecimal notation of «FFFF00». Get Magenta color by mixing red and blue (255,0,255) which equates to integer value 16711935 and to hexadecimal notation «FF00FF». Color tone can be changed wherein «FF77FF» (increasing intensity of green) will be a lighter magenta and «FF00FF» (decreasing intensity of green) will be a darker shade of magenta.

The VBA Hex function «Hex(number)» returns a string representing the hexadecimal value of a number. Hex function converts a decimal format to a hex notation. Converting a number to hex format with the Hex function viz. Hex(255), will return «FF», representing the color Red. It should be prefixed with &H and then («&HFF») entered in the Properties Window (right column), wherein it will appear as «&H000000FF&». Hex notation is always prefixed with &H, which indicates it is being used. The trailing ampersand (&) tells vba it’s a Long value/data type (4 byte) and not a 2-byte Integer data type, and has nothing to do with hexadecimal notation. Note: Instead of the RRGGBB notation (used in web and HTML programming) VBA uses BBGGRR notation, or &H00BBGGRR&. The Hex function also returns in BBGGRR notation. This explains why the color red appears as &H000000FF& in the Properties window whereas its html hexadecimal notation is FF0000 viz. RGB(255,0,0) using the RGB function. Using another example for color blue represented by RGB(0,0,255): this equates to integer value of 16711680 (=0*1+0*256+255*65536), and using the Hex function, Hex(16711680) returns FF0000 whereas the web/html hexadecimal notation of color blue RGB(0,0,255) is 0000FF. The hex notation displayed in the Properties Window (VB editor) is in BBGGRR format: &H00FF0000&.

Four ways to specify color in Properties Window — (i) in the property’s right column (in Properties Window) click the «Palette» tab and select a new color; (ii) select a predefined color from the «System» tab; (iii) enter a Long Integer which represents a valid color; or (iv) enter the hexadecimal notation in BBGGRR format preceded by &H. The hex notation displayed will be in BBGGRR format, viz. &H00FFFF0A& for aqua (variation of aqua) color.

_____________________________________________________________________

Applicability of Properties to UserForm and its Controls — A SnapShot:

 

Excel VBA Tutorial about Object PropertiesI’ve got to confess something to you:

I cover the topic of VBA objects extensively in Power Spreadsheets, including here and here. However, when working in Visual Basic for Applications, you can’t really do anything meaningful by knowing only what I explain in those Excel tutorials.

Let me explain what I mean:

There is no doubt that the concept of objects is central to VBA. After all, VBA is loosely based on the concept of object-oriented programming.

However, as explained by John Walkenbach in Excel VBA Programming for Dummies:

(…) you can’t do anything useful by simply referring to an object (…).

In order to actually start “doing something” with an object, you need to understand at least 1 of the following topics:

  • Object properties.
  • Object methods.

To be more precise:

In order to become great in VBA, you actually need to understand and master both properties and methods. This Excel tutorial covers 1 of these topics:

Object properties.

More particularly, in this blog post you’ll read about the following topics:

If you’re interested in reading about object methods, please click here.

Let’s start learning about the topic of VBA object properties by remembering what they actually are:

What Are VBA Object Properties

As I explain in this Excel VBA tutorial, properties are the named attributes of an object or, in other words, what you can use to describe an object, such as its:

  • Attributes.
  • Characteristics.
  • Qualities.

In Excel 2013 VBA and Macros, Excel authorities Bill Jelen and Tracy Syrstad liken properties to adjectives. In the regular English language, adjectives describe or clarify a noun.

In the context of Visual Basic for Applications, objects are the equivalent of nouns. Therefore, within VBA, properties (adjectives) describe objects (nouns).

The above comments apply to object collections (which are objects themselves) as well. In other words, collections also have properties that describe them.

As mentioned in Mastering VBA for Microsoft Office 2013, every object within Visual Basic for Applications has properties. This makes sense, after all, properties determine things such as:

  • How the object looks like.
  • How the object behaves like.
  • Whether you can or can’t see the object.

In fact, most objects have several properties, with each property determining a different characteristic of the object.

Richard Mansfield explains, in Mastering VBA for Microsoft Office 2013, how objects of the same type have the same set of properties. However, each of the individual objects stores their own individual values for each of those properties. In other words:

(…) each object is independent of the other objects.

As explained in Excel VBA Programming for Dummies, Excel 2013 Power Programming with VBA and Excel 2013 VBA and Macros, VBA allows you to do the following 2 things with the properties of an object:

Object Property Use #1: Read Them

This means, in other words, fetch or return the current settings of an object property.

As explained in the Excel 2013 Bible, you’d generally examine the current property of an object for purposes of taking a particular course of action depending on the value of that property.

However, properties can also be used to return objects. In fact, most VBA objects are actually accessed through the use of properties. For example, the macro samples that are used below in this Excel VBA tutorial use the Range.Interior property for these purposes.

Object Property Use #2: Modify Them

This means, more precisely, change the current setting of that property and set it to a certain value.

Based on the 2 uses above, you can classify VBA object properties in read/write, read-only or write-only properties. Let’s see what each of these means:

Read And Write VBA Object Properties

As mentioned by Richard Mansfield in Mastering VBA for Microsoft Office 2013, “many properties are read/write“. This means that you can carry out both of these actions (read or modify) in connection with such properties.

However, as you’ll see below, not all properties are like this. There are both read-only and write-only properties. As implied by the description, you can only:

  • Read (but not set) read-only properties.
  • Set (but not read) write-only properties.

I show you step-by-step examples of how to do both of this below.

How Do You Work With A VBA Object Property

In order to understand the syntax you should use in order to work with a VBA object property, let’s use 2 practical examples:

  • Example #1: We take a look at an example where the VBA code changes the current setting of a property.
  • Example #2: We see an example of a macro that reads and displays the current settings of that same property.

In both cases, I’ll provide additional information about the particular case. However, the general rule for referring to a VBA object property is clearly explained by John Walkenbach in the Excel 2013 Bible:

You refer to a property in your VBA code by placing a period (a dot) and the property name after the object’s name.

In other words, you generally:

  • Refer to the object and then to the property, as mentioned in Excel Macros for Dummies.
  • Separate the object from the property with a period (.).

As explained below, whenever you’re setting the value of a particular object property, you generally include an additional element: the property value you’re setting. However, even in such cases, you continue to use the basic syntax described above.

Let’s go to the examples and see how this syntax looks in practice:

VBA Object Property Syntax Case #1: Setting A Property Value

The following macro (called Find_Format_Formulas) finds, selects and formats all formulas in the active Excel worksheet. More precisely, this macro highlights in light yellow any cell that contains a formula.

VBA Sub procedure to find and format formulas

This Excel VBA Properties Tutorial is accompanied by an Excel workbook containing the data and macros I use (including the Find_Format_Formulas macro). You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

Let’s take a look at the practical results of executing the Find_Format_Formulas macro:

I’ve typed the following (random) formula using the SUM function. Notice how none of the cells that appear in the screenshot is highlighted.

Excel with sample SUM formula

The following screenshot shows the same cells after the Find_Format_Formulas macro is executed. Notice how, now, the cell with the formula is highlighted in light yellow.

Macro highlighting Excel formula

Described in plain English, the macro has changed the fill color of the cell.

Let’s describe what is happening in a slightly more structured manner to see what Visual Basic for Applications has done:

  • The cell itself is an object.
  • The fill color is an attribute that you can use to describe the cell. In other words, the fill color is a VBA object property.
  • The Find_Format_Formulas macro has modified the value of the fill color property.

Let’s go back to the VBA code of the Find_Format_Formulas and focus on the statement that determines the new value of the fill color VBA property. This statement is:

my_Range.Interior.ColorIndex = 36

The following screenshot shows the location of this statement within the Find_Format_Formulas Sub procedure:

VBA code with example of VBA object property

Let’s take a close look at each of the elements in this statement to understand its structure:

Element #1: Object (my_Range.Interior)

my_Range is an object variable. Object variables serve as a substitute for actual objects.

In this example, my_Range is a Range object.

The Range.Interior property is used for purposes of returning the interior of the relevant range. In the case of this example, this is the interior of the cells that contain formulas. This, in turn, is an Interior object.

In other words, this first element represents the interior of the cells that contain formulas. This the object whose attribute (color, in the example above) changes. This sentence can be reworded in VBA terms as follows:

my_Range.Interior represents the object whose property (fill color) is modified.

Element #2: Dot (.) Operator

As a general rule, Visual Basic for Applications uses the dot (.) operator to connect and separate the various items you can work with.

You can think of the dot (.) operator as the rough equivalent to the word “of” in plain English. The following are the basics of the dot (.) notation:

  • It’s hierarchical and usually begins with an object.

    As a consequence of the above, the hierarchy of VBA objects in Excel is of particular importance.

  • Once you’ve identified the object, you include a dot (.) to separate the object from the relevant property or method.

    Notice how, in the example above, we’ve used additional dots when identifying the object (my_Range.Interior). This happens because, depending on matters such as how you craft your object references and which particular object you’re working with, you may have to use additional dots when identifying the object.

  • After the dot, you type the relevant property or method.

In the case of this Excel tutorial, you already know that we’re working with properties (not methods). Therefore, what the next element in the statement is shouldn’t be a surprise to you:

Element #3: Property (ColorIndex)

You can use the ColorIndex property to either return or set the color of the relevant object (usually a border, font or interior).

In the example above, we’re modifying the actual property (not reading it). Therefore, let’s take a look at the last element of the statement to see how the property value is set…

Element #4: Property Value (= 36)

In order to be able to modify the value of a property, you must work with arguments. In Excel 2013 Power Programming with VBA, John Walkenbach explains that not all properties use arguments. However, some (such as ColorIndex) do.

In the cases where a property uses arguments, the main purpose of such argument is to specify the value of the property. According to Walkenbach, property arguments is an issue that often “leads to confusion among new VBA programmers”.

However, the basic syntax for specifying arguments for VBA object properties isn’t particularly complicated. In fact, the general rule is as simple as shown above:

You use an equal sign (=) to separate the property name from the property value.

As mentioned in Excel 2013 VBA and Macros and Microsoft Excel 2013 In Depth, the equal sign (=) is a good indication that you’re looking at a property value. If you see a colon (:) before the equal sign (:=), you’re likely looking at a method.

In other words, to set the value of a property, you:

  • Refer to the property.
  • Place an equal sign (=) after the VBA object property name.
  • Set the value of the object property.

Therefore, in the statement above, the ColorIndex property is used to set the color of the Interior object identified in the first part of the statement (the interior of the cells that contain formulas) to color 36 of the color palette. Color 36 is the light yellow that appears in the screenshot above.

In other words, the basic syntax you must follow in order to be able to set the value of a VBA property (as partially explained above) is:

Object.Property = Property_Value

The first part (Object.Property) is the general syntax that I describe above and that you use when reading a property value. In other words, this is the basic structure you need to know.

When setting the value of an object property, you only need to add the last elements (= Property_Value): an equal sign and the property value.

You won’t be able to modify absolutely all object properties using Visual Basic for Applications by using the syntax described above. There are some object properties that are read-only. For example:

  • In the Excel 2013 Bible, John Walkenbach lists the Row and Column properties of a single-cell Range object.
  • In Excel Macros for Dummies, Michael Alexander mentions the “Text property of cell”.

The consequence of a property being read-only, as you can probably imagine, is that:

  • You can read the object property…
  • But you can’t modify it.

Let’s turn, then, to the second case of property use:

VBA Object Property Syntax Case #2: Reading A Property Value

Let’s go back to the Excel workbook in which the sample Find_Format_Formulas macro was run:

The following screenshot shows the only worksheet of that workbook. Notice how there’s only 1 cell (B5) whose fill has been set to light yellow by the Find_Format_Formulas macro:

Example of modified object property in Excel

The following Sub procedure (named Display_ColorIndex) shows a message box displaying the value of the ColorIndex property for cell B5 of the worksheet named VBA Object Properties. The basic structure of this piece of VBA code is suggested by John Walkenbach in both Excel VBA Programming for Dummies and Excel 2013 Power Programming with VBA.

Example macro that reads object property setting

The following is the message box that Excel displays when the Display_ColorIndex macro is executed:

Message box with ColorIndex property

The value displayed (36) makes sense. Cell B5 of the worksheet named VBA Object Properties is the only cell with a light yellow fill. We already know from the previous macro Find_Format_Formulas, that this light yellow is color 36 in the color palette for the ColorIndex property.

Let’s focus, once again, on the most relevant section of the macro. The following image shows the part of the statement that is responsible for reading the value of the ColorIndex property of cell B5’s interior:

Syntax for VBA object property

This probably looks familiar.

You’ll notice that this is materially the same structure that we saw before when looking at how to modify the settings of an object property. Let’s take a look at the 3 elements of this statement to make it even clearer:

Element #1: Object (Worksheets(“VBA Object Properties”).Range(“B5”).Interior)

This structure is substantially similar to that I describe above. In other words:

  • The first part (Worksheets(“VBA Object Properties”).Range(“B5”)) of this section follows the general way of crafting references to Excel’s Range object.
  • The Range.Interior property is used for purposes of returning an Interior object. In this case, this object is the interior of cell B5 in the worksheet called VBA Object Properties.

    There is, however, a substantial difference: the Display_ColorIndex macro has no object variables whereas the Find_Format_Formulas macro in the previous section does.

Element #2: Dot (.) Operator

The dot (.) operator serves exactly the same purpose as in the Find_Format_Formulas macro above. In other words, it’s used to connect and separate element #1 above (the object) with element #3 below (the property).

Element #3: Property (ColorIndex)

The ColorIndex property can be used to set the color of an object (such as the interior of a cell). This is what the property does in the Find_Format_Formulas above.

However, ColorIndex can also be used to return the color of an object. This is the way in which the property is used in the Display_ColorIndex macro under analysis.

This analysis confirms what we’d seen above. More precisely, it confirms that the basic syntax that you can use to refer to Excel VBA properties is the same regardless of whether you are changing or examining the setting of that particular property. Just as a reminder, this basic syntax is:

Object.Property

I suggest you exercise care when creating references to objects and properties. Even though the basic syntax isn’t complicated, is important to make sure that you’re correctly identifying the relevant collections and the appropriate object from within the collection, as well as correctly using properties to refer to an object. If you fail to do this properly, you’ll usually receive an error message when trying to execute the macro.

For example, let’s assume that, instead of typing “VBA Object Properties” to identify the object from within the Worksheets collection I want to work with, I type the default “Sheet1”. In other words, the VBA code of the Display_ColorIndex macro looks as follows:

VBA code with wrong object reference

Sheet1 doesn’t exist within the example workbook that accompanies this Excel VBA Properties tutorial. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

Therefore, when I try to execute the Display_ColorIndex macro, Visual Basic for Applications returns the following error:

VBA error caused by wrong object reference

Obtaining an error in such a case makes sense. After all, as John Walkenbach explains in Excel VBA Programming for Dummies:

VBA just follows instructions, and it can’t work with a sheet that doesn’t exist.

Finally, remember that there are some instances in which you’ll not be able to read an object’s properties. In those cases, the property is deemed to be write-only.

In Excel 2013 Power Programming with VBA, John Walkenbach explains how this is the case, for example, in connection with the Value and Formula properties of certain cell Range objects. More precisely, you can only read the Value and Formula properties for a single-cell objects. This limitation (however) only applies to reading the property. You can actually modify the Value and Formula properties for multi-cell Range objects.

The consequences of a property being write-only are the following:

  • You can’t read the object property…
  • But you can modify it.

This is exactly the opposite of what happens in the case of read-only properties, which are described above.

Before we move on to the next topic, let’s take a quick look at 2 final clarifications regarding the syntax you should use when working with VBA object properties:

Default Object Properties And Properties That Return Values

Most VBA objects have a particular property that is their default. Therefore, theoretically, you can omit certain parts of the code. In other words, you can simply make reference to the VBA object, without including the property after it.

However, as mentioned in Excel 2013 Power Programming with VBA, including the VBA property explicitly in your code is a good programming practice. This is the case even if the property you’re making reference to is the default property.

Finally, note that Excel 2013 Power Programming also explains that in the case of properties that return a value, you must place parentheses around the arguments. This is an exception to the rules that I explain in the sections above.

Now that you know how to refer to and work with Excel VBA object properties, you may wonder…

How Do You Know Which Properties Are Available For A Particular VBA Object

According to John Walkenbach, there are:

(…) literally thousands of properties and methods available.

Fortunately, you won’t need to work with most of them. Most likely, you’ll end up working with a relatively small portion of the available VBA object properties again and again.

Additionally, even though each VBA object has its own properties, some properties are common to several objects. The following are some of the examples of common VBA properties. These examples are further explained in Excel VBA Programming for Dummies and Mastering VBA for Microsoft Office 2013:

  • The Visible property.
  • The Name property.
  • The Saved property.

However, since you’re likely to (from time to time) need some help to find out the properties that are available for a particular VBA object, let’s take a look at 3 ways in which you can get this information.

And in any case, remember that the macro recorder can help you identify/see what you need“.

Method #1: Use The Object Browser

As implied by its name, the Object Browser within the Visual Basic Editor allows you to browse through VBA objects. Perhaps more importantly, it shows you the properties, methods and events of each of those objects.

You can access the Object Browser in any of the following ways:

  • Click on the Object Browser button in the Standard toolbar.

    Access Object Browser in Visual Basic Editor

  • Go to the View menu and select “Object Browser”.

    Object Browser in Visual Basic Editor

  • Use the keyboard shortcut “F2”.

Once the Visual Basic Editor is displaying the Object Browser, you can have the VBE display all the relevant information about a particular object by following these 2 easy steps:

Step #1: Select The Excel Library

On the top left-hand corner of the Object Browser, you’ll notice a drop-down list that says “<All Libraries>”.

Object Browser to see properties

Click on this drop-down list and select “Excel”.

Select Excel library in VBE

Step #2: Select The Appropriate Object Class

Once you’ve selected the Excel library, the Object Browser displays all the Excel objects in the left side of the screen. Simply search for the one you want and click on it.

Once you’ve clicked on a particular object, the Object Browser lists all the properties and methods available for that object on the right side of the screen.

For example, the following image shows how the Object Browser looks like when I click on “Interior”. Notice how the ColorIndex property (which is used in both sample macros within this Excel tutorial) appears on the right side.

ColorIndex property for Interior object

Method #2: Use The Microsoft Developer Network

The Microsoft Dev Center contains an extensive amount of information about VBA objects and properties. The easiest way to find information about a particular object using this tool is by following these 3 simple steps:

Step #1: Enter An Object In The Visual Basic Editor

This step is self-explanatory. Simply type the name of the object you wish to find more information about.

Let’s assume that we want to find more information about the Range object while working in the sample Display_ColorIndex macro. Therefore, the VBA code looks as follows:

Object in VBA code

Step #2: Place The Cursor Within The Object Name

This step doesn’t require much further explanation.

The following screenshot shows how this looks like when the relevant object is Range and we’re working with the Display_ColorIndex macro:

Range object within VBA code

Step #3: Press The F1 Key

The F1 key is the keyboard shortcut to open the help system. You can find a comprehensive list of keyboard shortcuts in this blog post.

If the Visual Basic Editor finds that there are several possible matches for the keyword you’ve selected, it asks you to select a topic. This is what happens in the case of Range.

Context Help to find information about VBA object

If there’s no ambiguity (it’s clear which word you want to get information about), or once you’ve selected a topic in the Context Help dialog (as in the case above), you’re led to the relevant page within the Microsoft Developer Network.

For example, in the case above, once I choose the first option (“Range(object)”) and press the Help button on the upper right corner of the Context Help dialog, the Microsoft Developer Network displays the page that corresponds to this object. You can have the Microsoft Developer Network display all the properties that correspond to the Range object by clicking on, or expanding the menu, “Properties” on the left sidebar.

Range Object in Microsoft Developer Network

Method #3: Make The Visual Basic Editor Display A List Of Properties

Probably the easiest way of getting an idea of the properties of a particular object is by getting help from the Visual Basic Editor.

The VBE displays a list with all the items (such as properties and methods) that can be associated with a particular object once you’ve typed the dot (.) that follows that VBA object.

Let’s take a look at an example by going back to the VBA code of the Find_Format_Formulas macro. The following screenshot shows how the Visual Basic Editor displays a list of properties and methods immediately after I type the dot (.) that follows “my_Range.Interior”.

List of object properties in VBE

In order to be able to take advantage of this setting, your Visual Basic Editor must have the Auto List Members setting option enabled. I explain how to do this here.

This helps you get an idea of what are the properties and methods (in the example above, the VBE shows only properties) that you have available in a particular situation.

Conclusion

The concept of object properties is central to Visual Basic for Applications. Therefore, if you plan on working with VBA, you’ll spend a great deal of time dealing with object properties.

Despite being a relatively basic concept, the topic of properties can be quite overwhelming. As mentioned above, there are thousands of object properties available throughout Visual Basic for Applications.

The good news is that you don’t have to know absolutely all VBA object properties by heart in order to be able to do great work with Visual Basic for Applications. As long as you have a good understanding of the following 2 basic topics, you have a good base to start moving forward:

  • How to refer to and work with object properties.
  • How to search for and find the object properties you need.

Both of these matters were covered in this Excel tutorial.

Books Referenced In This Excel Tutorial

  • Alexander, Michael (2015). Excel Macros for Dummies. Hoboken, NJ: John Wiley & Sons Inc.
  • Jelen, Bill (2013). Excel 2013 In Depth. United States of America: Que Publishing.
  • Jelen, Bill and Syrstad, Tracy (2013). Excel 2013 VBA and Macros. United States of America: Pearson Education, Inc.
  • Mansfield, Richard (2013). Mastering VBA for Microsoft Office 2013. Indianapolis, IN: John Wiley & Sons Inc.
  • Walkenbach, John (2013). Excel 2013 Bible. Indianapolis, IN: John Wiley & Sons Inc.
  • Walkenbach, John (2013). Excel VBA Programming for Dummies. Hoboken, NJ: John Wiley & Sons Inc.
  • Walkenbach, John (2013). Excel 2013 Power Programming with VBA. Hoboken, NJ: John Wiley & Sons Inc.

Читает данные из открытого файла на диске в переменную.
Синтаксис
Get [#]номерФайла, [номерЗаписи], имяПеременной
Синтаксис инструкции Get содержит следующие элементы:
Элемент Описание
номерФайла Обязательный. Любой допустимый номер файла.
номерЗаписи Необязательный. Тип Variant (Long). Номер записи (для файлов в режиме Random) или номер байта (для файлов в режиме Binary), с которого следует начать чтение.
имяПеременной Обязательный. Допустимое имя переменной, в которую следует поместить считанные данные.
Дополнительные сведения

Данные, считываемые с помощью инструкции Get, обычно записываются в файл с помощью инструкции Put.
Первой записи (или байту) файла соответствует номер 1, второй (или второму) 2 и т.п. Если аргумент номерЗаписи опущен, читается запись (или байт), на которую был установлен указатель после выполнения последней инструкции Get или Put (или переведен при последнем вызове функции Seek). Наличие запятых-разделителей является обязательным, например:

Get #4,,FileBuffer

Для файлов, открытых в режиме Random, применимы следующие правила:

· Даже если длина данных, подлежащих чтению, меньше длины записи, указанной в предложении Len инструкции Open, инструкция Get начинает чтение каждой следующей записи с начала этой записи. Пространство между концом одной записи и началом следующей записи заполняется текущим содержимым буфера файла. Поскольку объем данных, используемых для заполнения, не может быть определен с достаточной степенью уверенности, рекомендуется, чтобы длина записи совпадала с длиной читаемых данных.

· Если данные считываются в строку переменной длины, инструкция Get сначала считывает 2-байтовый дескриптор, содержащий длину строки, а затем данные, которые следует поместить в эту переменную. Таким образом, длина записи, указанная в предложении Len инструкции Open, должна быть по крайней мере на 2 байта больше, чем фактическая длина этой строки.
· Если данные считываются в переменную Variant числового типа, инструкция Get сначала считывает 2 байта, указывающие подтип (VarType) этой переменной, а затем данные, которые следует поместить в эту переменную. Например, при чтении переменной Variant подтипа VarType 3 инструкция Get считывает 6 байт: 2 байта, указывающие подтип переменной Variant как VarType 3 (Long), и 4 байта, содержащие значение типа Long. Длина записи, указанная в предложении Len инструкции Open, должна по крайней мере на 2 байта превышать фактический размер, необходимый для размещения этой переменной.

Примечание. С помощью инструкции Get можно считать массив типа Variant с диска, однако нельзя прочитать скаляр типа Variant, содержащий массив. Кроме того, инструкцию Get нельзя использовать для чтения объектов с диска.

· Если данные считываются в переменную типа Variant подтипа VarType 8 (String), инструкция Get сначала считывает 2 байта, указывающие VarType, потом 2 байта, указывающие длину строки, а затем содержимое строки. Длина записи, указанная в предложении Len инструкции Open, должна быть по крайней мере на 4 байта больше, чем фактическая длина этой строки.
· Если данные считываются в динамический массив, инструкция Get сначала считывает дескриптор, длина которого равняется (2 + 8 * числоРазмерностей) байт. Длина записи, указанная в предложении Len инструкции Open , должна быть больше либо равна сумме всех байтов, необходимых для размещения массива данных и дескриптора массива. Например, для размещения описанного ниже массива требуется 118 байт

Dim MyArray(1 To 5,1 To 10) As Integer

118 байт распределяются следующим образом: 18 для дескриптора (2 + 8 * 2) и 100 байт для данных (5 * 10 * 2).

· Если данные считываются в массив фиксированного размера, инструкция Get считывает только данные. Дескриптор не считывается.
· Если данные считываются в переменную любого другого типа (кроме строки переменной длины и переменной типа Variant), инструкция Get считывает только данные. Длина записи, указанная в предложении Len инструкции Open, должна быть больше либо равна длине данных, подлежащих считыванию.
· Инструкция Get считывает элементы определяемых пользователем типов так, будто это отдельные переменные, за исключением того, что пространство между элементами не заполняется текущим содержимым буфера файла. На диске динамический массив типа, определенного пользователем (записанный с помощью инструкции Put) предваряется дескриптором, длина которого равняется (2 + 8 * числоРазмерностей) байт. Длина записи, указанная в предложении Len инструкции Open, должна быть больше либо равна сумме всех байтов, необходимых для размещения отдельных элементов, в том числе, массивов и их дескрипторов.

Для файлов, открытых в режиме Binary, применимы все перечисленные выше правила, за исключением следующих:

· Предложение Len инструкции Open игнорируется. Инструкция Get считывает все переменные с диска непрерывно, т.е. без заполнения пространства между записями текущим содержимым буфера файла.
· При чтении любых массивов, кроме являющихся элементами типов, определяемых пользователем, инструкция Get считывает только данные. Дескриптор не считывается.
· При считывании строк переменной длины, не являющихся элементами типов, определяемых пользователем, 2-байтовый дескриптор не считывается. Число считываемых байт равняется числу символов, уже содержащихся в строке. Например, следующие инструкции считают 10 байт из файла, которому соответствует номер 1:

VarString = String(10,» «)
Get #1,,VarString

Описывает имя, аргументы и текст программы, составляющий тело процедуры Property, которая задает ссылку на объект.

[Public | Private] [Static] Property Set имя [(списокАргументов)]
	[инструкции]
	[Exit Property] 
	[инструкции]
End Property

Параметры
Optional
Необязательный. Указывает, что при вызове процедуры аргумент может задаваться или не задаваться.
Public
Необязательный. Указывает, что процедура Property Set доступна для всех других процедур во всех модулях. При использовании в личном модуле (модуле, который содержит инструкцию Option Private) такая процедура является недоступной вне проекта.
Private
Необязательный. Указывает, что процедура Property Set доступна для других процедур только того модуля, в котором она описана.
Static
Необязательный. Указывает, что локальные переменные процедуры Property Set сохраняются в промежутках времени между вызовами этой процедуры. Атрибут Static не действует на переменные, описанные вне процедуры Property Set, даже если они используются в этой процедуре.
имя
Обязательный. Имя процедуры Property Set, удовлетворяющее стандартным правилам именования переменных, за исключением того, что это имя может совпадать с именем процедуры Property Get или Property Let из этого же модуля.
списокАргументов
Обязательный. Список переменных, представляющий аргументы, которые передаются в процедуру Property Set при ее вызове. Несколько имен переменных разделяются запятыми. Последний аргумент представляет собой ссылку на объект, используемую с правой стороны присвоения.

  • Optional — Необязательный. Указывает, что этот аргумент необязателен. При использовании этого элемента все последующие аргументы, которые содержит списокАргументов, также должны быть необязательными и быть описаны с помощью ключевого слова Optional. Отметим, что правая часть выражения Property Set не может иметь тип Optional.
  • ByVal — Необязательный. Указывает, что этот аргумент передается по значению.
  • ByRef — Необязательный. Указывает, что этот аргумент передается по ссылке. Описание ByRef используется в Visual Basic по умолчанию.
  • имяПеременной — Обязательный. Имя переменной, удовлетворяющее стандартным правилам именования переменных.
  • тип — Необязательный. Тип данных аргумента, передаваемого в процедуру; поддерживаются типы Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (в настоящее время не поддерживается), Date, String (только строки переменной длины), Object, Variant. Если отсутствует ключевое слово Optional, могут быть также указаны определяемый пользователем тип или объектный тип.
  • поУмолчанию — Необязательный. Любая константа или выражение, дающее константу. Используется только вместе с параметром Optional. Если указан тип Object, единственным значением по умолчанию может быть значение Nothing.

инструкции

Необязательный. Любая группа инструкций, выполняемых внутри тела процедуры Property.

Каждая инструкция Property Set должна определять по крайней мере один аргумент определяемой процедуры. Этот аргумент (или последний аргумент, если имеется более одного аргумента) содержит реальную ссылку на объект, которая будет присвоена свойству при вызове процедуры, определенной с помощью инструкции Property Set. Не допускается описание этого аргумента с типом Optional.

Замечания
Процедуры Property, тип которых не указан явно с помощью слов Public или Private, являются общими по умолчанию. Если не используется слово Static, значения локальных переменных не сохраняются между вызовами процедур.
Все выполняемые команды должны находиться в процедурах. Не допускается определение процедуры Property Set внутри другой процедуры Property, Sub или Function.
Инструкция Exit Property вызывает немедленный выход из процедуры Property Set. Выполнение программы продолжается с инструкции, следующей за инструкцией вызова процедуры Property Set. В любом месте процедуры Property Set допускается любое число инструкций Exit Property.
Подобно процедурам Function и Property Get, процедура Property Set является самостоятельной процедурой, которая может получать аргументы, выполнять последовательность инструкций и изменять значения своих аргументов. Однако в отличие от процедур Function и Property Get, которые возвращают значения, процедуру Property Set можно использовать только в левой части присвоения ссылки на объект (в инструкции Set).

Пример
В данном примере инструкция Property Set используется для описания процедуры, которая задает ссылку на объект.

' Свойству Pen могут быть присвоены значения свойства Pen разных объектов.
Property Set Pen(P As Object)
	Set CurrentPen = P	' Присваивает свойство Pen объекту.
End Property

I have a class module, named Normal, in VBA with the following code:

Private mLine As LineElement

Public Property Get Line() As LineElement
    Line = mLine
End Property

Public Property Set Line(ByRef vLine As LineElement)
    mLine = vLine
End Property

This class is used by the following code:

Sub Run
    Dim Line As LineElement
    Set Line = New LineElement

    Dim Norm As Normal
    Set Norm = New Normal
    Set Norm.Line = Line 'FAILS here with "Object Variable or With Block Variable not set"'
End Sub

Also, if I change the code in the Normal class module to:

Private mLine As LineElement

Public Property Get Line() As LineElement
    Line = mLine
End Property

Public Sub SetLine(ByRef vLine As LineElement) 'changed from property to sub'
    mLine = vLine
End Property

and the failing line to

Norm.SetLine( Line )

I get an «Object does not support this property or method» error. What exactly am I doing wrong in both of these cases?

Понравилась статья? Поделить с друзьями:
  • Pronounce the word either
  • Properties panel in word
  • Pronounce the word choose
  • Properties of word grouping
  • Pronounce the given word