Selection vba excel описание

Свойство Selection объекта Application, которое применяется в VBA для возвращения выбранного объекта на активном листе в активном окне приложения Excel.

Свойство Selection объекта Application возвращает выбранный в настоящее время объект на активном листе в активном окне приложения Excel. Если объект не выбран, возвращается значение Nothing.

Если выделить на рабочем листе диапазон «B2:E6», то обратиться к нему из кода VBA Excel можно через свойство Selection объекта Application, например, присвоить выбранный диапазон объектной переменной:

Sub Primer1()

Dim myRange As Object

    Set myRange = Selection

    MsgBox myRange.Address

End Sub

При использовании свойства Selection в коде VBA Excel указывать объект Application не обязательно. Результат работы кода:

На рабочем листе Excel может быть выбран не только диапазон ячеек, но и другие объекты: рисунок, надпись, диаграмма, элемент управления формы и другие.

Применение функции TypeName

Для программного выбора объекта в VBA Excel используется метод Select, а для определения типа ранее выбранного объекта — функция TypeName.

TypeName — это функция, которая возвращает данные типа String, предоставляющие информацию о типе переменной или типе объекта, присвоенного объектной переменной.

Выберем диапазон «D5:K9» методом Select и определим тип данных выбранного объекта с помощью функции TypeName:

Sub Primer2()

    Range(«D5:K9»).Select

    MsgBox TypeName(Selection)

End Sub

В качестве переменной для функции TypeName здесь используется свойство Selection. Результат работы кода:

Следующий пример кода VBA Excel очень хорошо иллюстрирует определение типа выбранного объекта с помощью функции TypeName. Он взят с сайта разработчиков, только в блок Select Case добавлены еще два элемента Case:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

Sub TestSelection()

    Dim str As String

    Select Case TypeName(Selection)

        Case «Nothing»

            str = «Объект не выбран.»

        Case «Range»

            str = «Выбран диапазон: « & Selection.Address

        Case «Picture»

            str = «Выбран рисунок.»

        Case «ChartArea»

            str = «Выбрана диаграмма.»

        Case «TextBox»

            str = «Выбрана надпись.»

        Case Else

            str = «Выбран объект: « & TypeName(Selection) & «.»

    End Select

    MsgBox str

End Sub

Если из предыдущей процедуры VBA Excel удалить переводы отдельных типов объектов и учесть, что рабочий лист без выбранного объекта встречается редко, то ее можно значительно упростить:

Sub TestSelection2()

    MsgBox «Выбран объект: « & TypeName(Selection) & «.»

End Sub

Пример рабочего листа без выбранного объекта: лист диаграммы, на котором диаграмма не выбрана (выделение снимается кликом по одному из полей вокруг диаграммы). Для такого листа в информационном окне MsgBox будет выведено сообщение: Выбран объект: Nothing.

Свойство Selection при выборе листа

Если метод Select применить к рабочему листу, то свойство Application.Selection возвратит объект, который ранее был выбран на данном листе. Проверить это можно с помощью следующего примера:

Sub Primer3()

    Worksheets(3).Select

    Select Case TypeName(Selection)

        Case «Range»

            MsgBox «Выбран диапазон: « & Selection.Address

        Case Else

            MsgBox «Выбран объект: « & TypeName(Selection) & «.»

    End Select

End Sub

Свойство Selection при выборе книги

Выбрать рабочую книгу Excel методом Select невозможно, так как у объекта Workbook в VBA нет такого метода. Но мы можем выбрать книгу, сделав ее активной с помощью метода Activate:

Sub Primer4()

    Workbooks(«Книга2.xlsx»).Activate

    Select Case TypeName(Selection)

        Case «Range»

            MsgBox «Выбран диапазон: « & Selection.Address

        Case Else

            MsgBox «Выбран объект: « & TypeName(Selection) & «.»

    End Select

End Sub

В данном случае, свойство Application.Selection возвратит объект, который ранее был выбран на активном листе активированной книги.

Обычно, свойство Application.Selection используется для работы с выделенным диапазоном ячеек, а для обращения к одной активной ячейке используется свойство Application.ActiveCell.


VBA Selection

Excel VBA Selection Property

VBA Selection is used for selecting the range from excel worksheet. We can do anything and whatever with the selected range. But while using VBA Selection, we will not be seeing the list of functions we want to perform from where we can choose any as per our need. For this, we need to type that thing manually and it should be correct. So while using VBA Selection, we have to make sure that we will be using the correct function to avoid any kind of error.

How to Use Selection Property in Excel VBA?

Below are the different examples to use Selection property in excel by using VBA code.

You can download this VBA Selection Excel Template here – VBA Selection Excel Template

Excel VBA Selection – Example #1

In this example, we will see a very simple method of applying VBA Selection. For this follow the below steps:

Step 1: Go to the VBA window and open a new Module from the list of Insert menu as shown below.

VBA Selection Example 1-1

Step 2: Now in the newly opened module write the subcategory for VBA Selection as shown below.

Code:

Sub VBASelection()

End Sub

VBA Selection Example 1-2

Step 3: Select any range of cells. It can be any random or specific range of cells with the help of  Select command.

Code:

Sub VBASelection()

Range("A1:C3").Select

End Sub

Range of cells

Step 4: Now, we would try to insert some text in the selected range of cell. For this in the next line of code write Selection.Value. This is used for selecting the cells for putting the value in.

Code:

Sub VBASelection()

Range("A1:C3").Select
Selection.Value

End Sub

VBA Selection Example 1-4

Step 5: At last, we will write any text which we would like to see in the selected range of cell. Let that text be “Excel VBA Selection”.

Code:

Sub VBASelection()

Range("A1:C3").Select
Selection.Value = "Excel VBA Selection"

End Sub

VBA Selection Example 1-5

Step 6: Now run the code by clicking on the Play button which is placed below the menu bar as shown below.

VBA Selection Example 1-6

We will see, from cell A1 to C3, our selected text value has been inserted and the whole is selected as well.

Excel VBA Selection – Example #2

In this example we will see, how Offset function will work along with VBA Selection. For this, follow the below steps:

Step 1: Write the subcategory of VBA Selection as shown below.

Code:

Sub VBASelection2()

End Sub

VBA Selection Example 2-1

Step 2: Select the range of cell as per your need or else we can keep off using the same range of cells which we had seen in the above example.

Code:

Sub VBASelection2()

Range("A1:C3").Select

End Sub

VBA Selection Example 2-2

Step 3: Now choose Offset function along with Selection as shown below. By this Offset function, we would try to offset or move the selection from the next matrix.

Code:

Sub VBASelection2()

Range("A1:C3").Select
Selection.Offset

End Sub

Offset function

Step 4: After that select the offset location where we want to move the selection box from range cells A1 to C3. Let’s try to move it by 1 row and 1 column away from the current position.

Code:

Sub VBASelection2()

Range("A1:C3").Select
Selection.Offset(1, 1).Select

End Sub

Select offset location

Step 5: Now again run the code by pressing F5 key or by clicking on Play Button.

VBA Selection Example 2-5

We will see, now our new selection will be from cell B2 to D4 as shown below. And we had used Select command so that range is in a current selected mode.

Excel VBA Selection – Example #3

In this example, we will see how could we use and change the cell’s interior color with the help of VBA Selection. For this, follow the below steps:

Step 1: Write the subcategory of VBA Selection or in any name as per your choice as shown below.

Code:

Sub VBASelection3()

End Sub

VBA Selection Example 3-1

Again, we will keep on using the same range of cells as we have seen previously with the same inserted text.

Step 2: Select the range of required cell, which is from cell A1 to C3 here.

Code:

Sub VBASelection3()

Range("A1:C3").Select

End Sub

VBA Selection Example 3-2

Step 3: Now for changing the interior color of any cell, we need to use Interior.Color function together along with Selection. This will allow us to use all available vb Color we have in VBA.

Code:

Sub VBASelection3()

Range("A1:C3").Select
Selection.Interior.Color

End Sub

VBA Selection Example 3-3

Step 4: Here we have a variety of colors but all are BASE COLORS. To select any base color we will use vb followed by the name of the color. Let’s consider the interior color to be Green as shown below.

Code:

Sub VBASelection3()

Range("A1:C3").Select
Selection.Interior.Color = vbGreen

End Sub

Interior Color Green

Step 5: Now again run the code by pressing F5 key or by clicking on the Play Button.

VBA Selection Example 3-5

We will see, our selected range of cells are colored as Green.

Excel VBA Selection – Example #4

In this example, we will insert a text in any range of cells and simultaneously we will change the font color for those cell text as well. For this, follow the below steps:

Step 1: Write the subcategory of VBA Selection as shown below.

Code:

Sub VBASelection4()

End Sub

VBA Selection Example 4-1

Step 2: Again select the range of cells where we want to see all this happening. Here, we are again considering the same range.

Code:

Sub VBASelection4()

Range("A1:C3").Select

End Sub

Select the range of cells

Step 3: Again insert any text as we have seen in example-1. We will again use the same line of code here.

Code:

Sub VBASelection4()

Range("A1:C3").Select
Selection.Value = "Excel VBA Selection"

End Sub

VBA Selection Example 4-3

Step 4: Now with the help of Selection use Font.Color function together as shown below. By this, we would be able to select the color which we want to give to selected cell fonts.

Code:

Sub VBASelection4()

Range("A1:C3").Select
Selection.Value = "Excel VBA Selection"
Selection.Font.Color

End Sub

Font.Color function

Step 5: Again, we will use VBA base colors for cell font colors. Let’s use Red color this time starting with vb as shown below.

Code:

Sub VBASelection4()

Range("A1:C3").Select
Selection.Value = "Excel VBA Selection"
Selection.Font.Color = vbRed

End Sub

VBA base colors for cell font colors

Step 6: Now again run the code by pressing F5 key or by clicking on Play Button.

VBA Selection Example 4-6

We will see, in the selected range of cells we will have our text inserted and the color those cells are now Red from default Black.

Pros & Cons of Excel VBA Selection

  • This the direct way of selecting any function.
  • This is applicable to all type of functions.
  • VBA Selection is a much easier way of coding as compared to other forms.
  • As it does not allow the list of possible functions after it, so it becomes little complex to use VBA Selection.

Things to Remember

  • Make sure you use exact function after VBA Selection, to avoid getting error.
  • It is easy and possible to use complex code structure VBA Selection.
  • Once implementation is done, save the file in Macro enabled excel so that you will not lose written code ever.

Recommended Articles

This is a guide to VBA Selection. Here we discuss how to use selection property in Excel by using VBA code along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA Conditional Formatting
  2. VBA Get Cell Value
  3. VBA Named Range
  4. VBA RGB

In VBA, we can select any range of cells or a group of cells and perform different operations on them. For example, the selection is a range object, so we use the Range method to select the cells as it identifies the cells and the code to select the cells is the “Select” command. The syntax to use for selection is range(A1:B2).select.

Table of contents
  • What is Excel VBA Selection Property?
    • Examples of Selection Property in VBA
      • Example #1
      • Example #2
      • Example #3
    • Recommended Articles

What is Excel VBA Selection Property?

Selection is the property available with VBA. Once the range of cells is selected, we must decide what to do. Using this VBA Selection property, we can do everything we can with selected cells. One of the problems with the Selection property is we do not get to see the IntelliSense list. So, when writing the code, we must be sure of what we are doing without the IntelliSense list.

VBA Selection

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Selection (wallstreetmojo.com)

Examples of Selection Property in VBA

We look at the examples of selection in Excel VBA.

You can download this VBA Selection Excel Template here – VBA Selection Excel Template

Example #1

Here is a simple example of a “selection” property with VBA. Of course, we want to first select the cells from A1 to B5 to write the VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more like this.

Range (“A1:B5”).Select

Code:

Sub Selection_Example1()

  Range("A1:B5").Select

End Sub

This code will select the VBA range of cellsThe selection range is the desired area by the user to put effects, add data, or make changes in those specific cells only. The range is defined by formulas by the addresses of two cells separated by a colon. The cell where the selection range begins is still active.read more from A1 to B5.

VBA Selection Example 1

If we want to insert the value of “hello” to these cells, we can write the code like this.

Code:

Sub Selection_Example1()

  Range("A1:B5").Value = "hello"

End Sub

VBA Selection Example 1-1

Similarly, once the cells are selected, it becomes Selection.”

Code:

Sub Selection_Example1()

  Range("A1:B5").Select

  Selection.Value = "Hello"

End Sub

First, we have selected the range of cells from A1 to B5. So, this line will select the cells.

VBA Selection Example 1-2

Once these cells are selected, we can refer to these cells by using the property “Selection” in Excel VBA. So, using the Selection property, we can insert the value of “Hello” to these cells.

VBA Selection Example 1-3

It is the general overview of the “Selection” property in VBA.

Example #2

Now, we will see the VBA “Selection” property with variables. But, first, define the VBA variable as RangeRange is a property in VBA that helps specify a particular cell, a range of cells, a row, a column, or a three-dimensional range. In the context of the Excel worksheet, the VBA range object includes a single cell or multiple cells spread across various rows and columns.read more.

Code:

Sub Selection_Example2()

  Dim Rng As Range

End Sub

VBA Selection Example 2

The range is an object variable since it is an object variable. Therefore, we need to set the range of cells using the “Set” keyword.

We will set the range as “Range(“A1:A6”).

Code:

Sub Selection_Example2()

  Dim Rng As Range
  Set Rng = Range("A1:A6")

End Sub

VBA Selection Example 2-1

The variable “Rng” refers to the range of cells A1 to A6.

Now, we will write the code to insert the value of “Hello.”

Code:

Sub Selection_Example2()

  Dim Rng As Range
  Set Rng = Range("A1:A6")
  Rng.Value = "Hello"

End Sub

VBA Selection Example 2-2

It will insert the value of “Hello” to the cells A1 to A6.

VBA Selection Example 2-3

It does not matter where you are running the code. The active worksheet will insert the value “Hello” to cells A1 to A6.

But imagine the situation where you have to insert the word “Hello” wherever you select the cells with just a button click.

For this, we cannot set a specific range of cells. Rather we need to set the range as “Selection.”

Code:

Sub Selection_Example2()

  Dim Rng As Range
  Set Rng = Selection

End Sub

VBA Selection Example 2-4

The variable “Rng” refers to the active cell or wherever we select the cells. For example, using this property (Selection) in Excel VBA, we can insert the value “Hello.”

Code:

Sub Selection_Example2()

  Dim Rng As Range
  Set Rng = Selection

  Selection.Value = "Hello"

End Sub

VBA Selection Example 2-5

It will insert the word “Hello” into the cells of our selection. Now, we will select the cells from B2 to C6 and run the code. First, it will insert the “Hello” value.

VBA Selection Example 2-6

Example #3

Now, we will see how we can change the interior color of the selected cells. Now, we want to change the interior color of the cells we will select. For this first, we have declared the variable as Range and set the range reference as “Selection.”

Code:

Sub Selection_Example3()

  Dim Rng As Range
  Set Rng = Selection

End Sub

Example 3

Now, access the Interior property using the VBA Selection property.

Code:

Sub Selection_Example3()

  Dim Rng As Range
  Set Rng = Selection

  Selection.Interior

End Sub

Example 3-1

Once the “Interior” property is selected, we need to decide what we need to do with this property. Since we need to change the color of the selected cell’s interior, select the property “Color.”

Code:

Sub Selection_Example3()

  Dim Rng As Range
  Set Rng = Selection

  Selection.Interior.Color

End Sub

Example 3-2

Set the color property as “vbGreen.”

Code:

Sub Selection_Example3()

  Dim Rng As Range
  Set Rng = Selection
 
  Selection.Interior.Color = vbGreen

End Sub

Example 3-3

So this will change the interior color of the selected cells to “vbGreen.”

Example 3-4

Example 3-5

Like this, we can use the Excel VBA “Selection” property in coding and do many more things easily.

Note: One of the biggest threats with the “Selection” property is we don’t get the IntelliSense list access while coding. As a new learner, it is almost impossible to remember all the properties and methods of the Selection property, so you need to be proficient in VBA to start using the “Selection” property.

Recommended Articles

This article is a guide to VBA Selection. Here, we discussed what Selection Property is in Excel VBA, with some practical examples and a download template. Below are some useful Excel articles related to VBA: –

  • VBA Text Function Examples
  • VBA Operators
  • Close UserForm in VBA

В VBA мы можем выбрать любой диапазон ячеек или группу ячеек и выполнять над ними различные операции. Например, выделение представляет собой объект диапазона, поэтому мы используем метод Range для выбора ячеек, поскольку он идентифицирует ячейки, а код для выбора ячеек — это команда «Выбрать». Для выбора используется следующий синтаксис: range(A1:B2).select.

Оглавление

  • Что такое свойство выбора Excel VBA?
    • Примеры свойства Selection в VBA
      • Пример №1
      • Пример #2
      • Пример №3
    • Рекомендуемые статьи

Что такое свойство выбора Excel VBA?

Выбор — это свойство, доступное в VBA. Как только диапазон ячеек выбран, мы должны решить, что делать. Использование этого VBA «Отбор» свойство, мы можем делать все, что можем, с выбранными ячейками. Одна из проблем со свойством Selection заключается в том, что мы не видим список IntelliSense. Итак, при написании кода мы должны быть уверены в том, что делаем без списка IntelliSense.

Выбор VBA

Примеры свойства Selection в VBA

Смотрим примеры выделения в Excel VBA..free_excel_div{background:#d9d9d9;font-size:16px;border-radius:7px;position:relative;margin:30px;padding:25px 25px 25px 45px}.free_excel_div:before {content:»»;фон:url(по центру без повтора #207245;ширина:70px;высота:70px;позиция:абсолютная;сверху:50%;отступ-сверху:-35px;слева:-35px;граница:5px твердый #fff; радиус границы: 50%}

Вы можете скачать этот шаблон Excel для выбора VBA здесь — Шаблон Excel для выбора VBA

Пример №1

Вот простой пример свойства «выбор» в VBA. Конечно, мы хотим сначала выбрать ячейки от A1 до B5, чтобы написать код VBA. Запись Код VBAКод VBA относится к набору инструкций, написанных пользователем на языке программирования приложений Visual Basic в редакторе Visual Basic (VBE) для выполнения. конкретная задача. читать дальше, как это.

Диапазон («А1:В5»).Выбирать

Код:

Sub Selection_Example1 () Range («A1: B5»). Выберите End Sub

Этот код выберет диапазон ячеек VBA. Диапазон ячеек VBA. Диапазон выбора — это желаемая пользователем область для добавления эффектов, добавления данных или внесения изменений только в эти конкретные ячейки. Диапазон определяется формулами по адресам двух ячеек, разделенных двоеточием. Ячейка, с которой начинается диапазон выбора, по-прежнему активна. Подробнее от A1 до B5.

Пример выбора VBA 1

Если мы хотим вставить в эти ячейки значение «привет», мы можем написать такой код.

Код:

Sub Selection_Example1() Range(«A1:B5»).Value = «hello» End Sub

Пример выбора VBA 1-1

Точно так же, как только ячейки выбраны, становится «Отбор».

Код:

Sub Selection_Example1() Range («A1: B5»). Выберите Selection.Value = «Hello» End Sub

Во-первых, мы выбрали диапазон ячеек от A1 до B5. Итак, эта строка будет выделять ячейки.

Пример выбора VBA 1-2

После того, как эти ячейки выбраны, мы можем ссылаться на эти ячейки, используя свойство «Выбор» в Excel VBA. Итак, используя свойство Selection, мы можем вставить в эти ячейки значение «Hello».

Пример выбора VBA 1-3

Это общий обзор свойства «Выбор» в VBA.

Пример #2

Теперь мы увидим свойство VBA «Выбор» с переменными. Но сначала определите переменную VBA как RangeVBA Variable As RangeRange — это свойство в VBA, которое помогает указать конкретную ячейку, диапазон ячеек, строку, столбец или трехмерный диапазон. В контексте рабочего листа Excel объект диапазона VBA включает одну или несколько ячеек, распределенных по разным строкам и столбцам. Подробнее.

Код:

Sub Selection_Example2() Dim Rng As Range End Sub

Пример выбора VBA 2

Диапазон является объектной переменной, поскольку он является объектной переменной. Поэтому нам нужно установить диапазон ячеек с помощью ключевого слова «Set».

Мы установим диапазон как «Диапазон(«А1:А6»).

Код:

Sub Selection_Example2() Dim Rng As Range Set Rng = Range(«A1:A6») End Sub

Пример выбора VBA 2-1

Переменная «Кольцо” относится к диапазону ячеек от А1 до А6.

Теперь мы напишем код для вставки значения «Привет».

Код:

Sub Selection_Example2() Dim Rng As Range Set Rng = Range(«A1:A6») Rng.Value = «Hello» End Sub

Пример выбора VBA 2-2

Он вставит значение «Привет» в ячейки от A1 до A6.

Пример выбора VBA 2-3

Неважно, где вы запускаете код. Активный рабочий лист вставит значение «Привет» в ячейки с A1 по A6.

Но представьте ситуацию, когда вам нужно вставить слово «Привет» везде, где вы выбираете ячейки, одним нажатием кнопки.

Для этого мы не можем задать определенный диапазон ячеек. Скорее нам нужно установить диапазон как «Выбор».

Код:

Sub Selection_Example2() Dim Rng As Range Set Rng = Selection End Sub

Пример выбора VBA 2-4

Переменная «Rng» относится к активной ячейке или везде, где мы выбираем ячейки. Например, используя это свойство (Выделение) в Excel VBA, мы можем вставить значение «Привет».

Код:

Sub Selection_Example2() Dim Rng As Range Set Rng = Selection Selection.Value = «Hello» End Sub

Пример выбора VBA 2-5

Он вставит слово «Привет» в ячейки нашего выделения. Теперь мы выберем ячейки от B2 до C6 и запустим код. Сначала он вставит значение «Hello».

Пример выбора VBA 2-6Пример №3

Теперь мы увидим, как мы можем изменить внутренний цвет выбранных ячеек. Теперь мы хотим изменить внутренний цвет ячеек, которые мы выберем. Для этого сначала мы объявили переменную как Range и установили ссылку на диапазон как «Selection».

Код:

Sub Selection_Example3() Dim Rng As Range Set Rng = Selection End Sub

Пример 3

Теперь получите доступ к «Интерьер» с помощью свойства выбора VBA.

Код:

Sub Selection_Example3() Dim Rng As Range Set Rng = Selection Selection.Interior End Sub

Пример 3-1

После выбора свойства «Интерьер» нам нужно решить, что нам нужно делать с этим свойством. Так как нам нужно изменить цвет внутренней части выбранной ячейки, выбираем свойство «Цвет».

Код:

Sub Selection_Example3() Dim Rng As Range Set Rng = Selection Selection.Interior.Color End Sub

Пример 3-2

Установите свойство цвета как «vbЗеленый».

Код:

Sub Selection_Example3() Dim Rng As Range Set Rng = Selection Selection.Interior.Color = vbGreen End Sub

Пример 3-3

Так что это изменит внутренний цвет выбранных ячеек на «вбГрин».

Пример 3-4Пример 3-5

Таким образом, мы можем использовать свойство «Выбор» Excel VBA в кодировании и легко делать многие другие вещи.

Примечание. Одна из самых больших угроз со свойством «Выбор» заключается в том, что мы не получаем доступ к списку IntelliSense во время кодирования. Как новичок, почти невозможно запомнить все свойства и методы свойства «Выбор», поэтому вам необходимо владеть VBA, чтобы начать использовать свойство «Выбор».

Рекомендуемые статьи

Эта статья представляет собой руководство по выбору VBA. Здесь мы обсудили, что такое свойство выбора в Excel VBA, с некоторыми практическими примерами и шаблоном для загрузки. Ниже приведены некоторые полезные статьи Excel, связанные с VBA:

  • Примеры текстовых функций VBA
  • Операторы VBA
  • Закрыть пользовательскую форму в VBA

Понравилась статья? Поделить с друзьями:
  • Selection typetext vba word
  • Selection range word vba
  • Selection pastespecial vba excel
  • Selection moveright vba word
  • Selection list in word