Get property vba excel

Читает данные из открытого файла на диске в переменную.
Синтаксис
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

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.

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

[Public | Private] [Static] Property Get имя [(списокАргументов)] [As тип]
	[инструкции]
	[имя = выражение]
	[Exit Property] 
	[инструкции]
	[имя = выражение]
End Property

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

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

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

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

Пример
В данном примере инструкция Property Get используется для описания процедуры, предназначенной для определения значения свойства. Эта процедура возвращает текущий цвет пера как строку.

Dim CurrentColor As Integer
Const BLACK = 0, RED = 1, GREEN = 2, BLUE = 3

' Возвращает текущий цвет пера как строку.
Property Get PenColor() As String
	Select Case CurrentColor
		Case RED
			PenColor = "Red"
		Case GREEN
			PenColor = "Green"
		Case BLUE
			PenColor = "Blue"
	End Select
End Property

' Следующий код определяет цвет пера с помощью процедуры Property Get.
ColorName = PenColor

The idea of object orientation is that an object hides it’s members from the outside world. The GET and SET properties act as a «gateway». This, no routine can simply override change the object underneath MyVBAinstance.InnerClass. What you need to do is:

Dim objTemp as As MyCOMclass
Set objTemp = New MyCOMclass 'this will reserve the memory and store the pointer in objTemp
Call COMinstance.CopyTo(objTemp) 'this will fill the allocated memory
Set MyVBAinstance.InnerClass = objTemp 'this will copy the pointer from objTemp to MyVBAinstance.InnerClass

If you want to expose some private members of your class, you need to provide the PROPERTY GET and PROPERTY SET/PROPERTY LET methods as you are doing. GET will be called every time you access the property — and PROPERTY SET/PROPERTY LET is called when you assign an object/value to the property.

If the property is an object, you need to use PROPERTY SET — if it is of a native type (Integer, String, etc.) you must use PROPERTY LET.

In the same way, you then need to assign objects to the property with SET (e.g. Set MyVBAInstance.InnerClass = anotherObject), but native types without SET (e.g. ‘ MyVBAInstance.Name = «Test»`)

Thus, in your code replace LET with SET here:

Public Property Set InnerClass(value As MyCOMclass)
    Set mMyCOMclass = value
End Property

and then also use the SET keyword in your code:

Set MyVBAinstance.InnerClass = COMinstance.Clone()

Object Properties

A property refers to what an object has.

As an analogy, a car has a predefined set of properties such as color, size, type, engine, etc.

Likewise, an Excel object could have its own set of properties, such as color, font, and value.

Properties come after the object hierarchy.

This means that the object is specified first, followed by a period, then the property name, and the details or value assigned to it.

It also has to be specific in cases where there might be some ambiguity.

Taking a car and a shoe as examples:

Car.Color – might be too broad

Car.Interior.Color = Black – this makes sure that Excel knows which part of the car is being referred to.

Property Details

There are different property scenarios in Excel

  1. Some properties don’t have details
    • Range(“A1”).Address
    • Range(“A1”).Value
  2. Some properties return an object – this occurs when an object’s property is also an object with its own properties
    • Range(“A2”).Interior.Color – The Range A2 has Interior as its property, while Interior has Color as its property.
    • Range(“A2”).Font.Color

An interior property returns an interior object.

More details on this can be found through Microsoft Help.

Property Type

A property can be either read-only, write, or both.

Below are some use cases:

  • Range(“A1”).Value = ActiveCell.Address
    • This reads the address of the active cell and puts it as the value of cell A1.
  • Range(“A1”).Interior.Color = vbRed
    • This assigns the color red to cell A1’s interior.
  • Range(“A1”).Font.Color = vbBlue
    • This changes the font color of cell A1 to blue.

Object Methods

A method dictates what to do with an object or what an object does.

Taking a car for an example, its methods can be:

  • Start
  • Stop
  • Crash

Method arguments

Some methods don’t have arguments, while some methods have additional arguments or information.

For example, how do you want to start the car?

Quickly or slowly?

This then becomes:

Car.Stop Quickly.

Methods can also change properties.

For a car, the “Crash” method would change the “Size” property of the car.

Ways of writing arguments

  • Using a space
    • Car.Stop Quickly
  • Assign a name of an argument and assign a value using :=
    • Car.Stop StopStyle:= Quickly

Below are some examples:

  • Clear – no further arguments
    • Range(“A2”).Clear
  • Delete([Shift]) – can have 1 argument that determines if you want to shift to the left, right, etc.
    • Range(“A2”).Delete xlShiftToLeft
      • This deletes cell A2 and shifts the table to the left.
  • Copy([Destination])– 1 argument for destination
    • Range(“A3”).Copy Range(“B3”)
      • This copies cell A3 to cell B3.
  • Copy([Before], [After])– 2 optional and exclusive arguments which can be written in two ways
    • Sheet1.Copy After:=Sheet3
      • Copy Sheet1 Sheet3.
    • Sheet1.Copy , Sheet2
      • Skip the [Before] argument and skip to the [After] argument
  • PasteSpecial – detailed pasting (formatting, transposed, etc.)
  • After – detailed pasting (formatting, transposed, etc.)

Published on: April 5, 2018

Last modified: February 23, 2023

Microsoft Most Valuable Professional

Leila Gharani

I’m a 5x Microsoft MVP with over 15 years of experience implementing and professionals on Management Information Systems of different sizes and nature.

My background is Masters in Economics, Economist, Consultant, Oracle HFM Accounting Systems Expert, SAP BW Project Manager. My passion is teaching, experimenting and sharing. I am also addicted to learning and enjoy taking online courses on a variety of topics.

Понравилась статья? Поделить с друзьями:
  • Get pivot table excel
  • Get pictures out of word
  • Get past the word
  • Get out the word about перевод
  • Get out off my word