Excel vba get selected value

Содержание

  1. Excel vba get selected value
  2. Method 1:
  3. Method 2:
  4. Method 3:
  5. Offset method:
  6. VBA Cell Value – Get, Set, or Change
  7. Set Cell Value
  8. Range.Value & Cells.Value
  9. Set Multiple Cells’ Values at Once
  10. Set Cell Value – Text
  11. Set Cell Value – Variable
  12. Get Cell Value
  13. VBA Coding Made Easy
  14. Get ActiveCell Value
  15. Assign Cell Value to Variable
  16. Other Cell Value Examples
  17. Copy Cell Value
  18. Compare Cell Values
  19. VBA Code Examples Add-in
  20. VBA Listbox – Selected Item
  21. Create List Box in a VBA Form
  22. Add Values to the List Box
  23. Select Values from the List Box
  24. Work with the Selected Values in VBA
  25. Assigning the Value to a Variable
  26. VBA Coding Made Easy
  27. Use a Command Button to Return the Value to Excel
  28. Select Multiple Values
  29. VBA Code Examples Add-in
  30. Get Cell Value in Excel VBA
  31. Get Cell Value with Excel VBA
  32. Examples of getting Cell Value in Excel VBA
  33. Example #1 – Using RANGE or CELLS Property
  34. Example #2 – Get Value from Cell in Excel VBA
  35. Example #3 – Get Value from One Cell to Another Cell
  36. Things to Remember
  37. Recommended Articles

Excel vba get selected value

There are three methods to read the selected values from a combobox in VBA. Please go through the following blog to know how you can do it.

Method 1:

Consider, we have a dropdown list having days mentioned in it. The value selected in the dropdown is ‘Sunday’. Now, we will try to read the selected value from the dropdown list using Excel VBA.

To read the selected day from the dropdown list into a variable, we can use the following snippet.

In the above code, we are creating an object reference for the dropdown “Drop Down 1”.

If you observe the code, we are using OLEFormat.Object. OLEFormat property is used when we are working with shapes (ComboBox, ListBox and so on) , inline shapes, or fields to return the OLEFormat object.

ddval’ is the variable that stores the value of the selected dropdown.

dd.List(dd.ListIndex)

Here, List returns an item from List index. List index is an expression that returns index of the objects in the list.

As we can see from the image above the variable ‘ddval’ has value ‘Sunday’.

Method 2:

In this method we will use ‘ListFillRange’. This property ‘ListFillRange’ reads the contents of every cell in the range designated for the list and inserts the cell values into the list box. Before fetching the selected dropdown value, we have to assign the range of dropdown values to property ‘ListFillRange’

Say, if the list of options are in Column Q starting from Q1 to Q10, then we define the listfillrange for the dropdown.

Once the ListFillRange is assigned, the selected dropdown value is fetched as below. ‘ddval’ is the variable that stores the dropdown value from the dropdown list.

Method 3:

In this method, we will use cell link to read the dropdown value to the variable.

Based on the selection in the dropdown list the cell link value in ‘I1’ changes. The cell link value in ‘I1’ can be used to read the selected dropdown value.

Offset method:

Here, we use ‘ListFillRange’ to identify the range and assign its value to the ‘rr’ variable. ‘x’ is the variable used to find the offset row location.

Based on ‘x’ value and by using offset function, the value of the dropdownlist is found as below

We are taking the dropdown value into the ‘ddval’ variable as shown in the image below.

This is how we get combobox selected value in VBA. If you have any queries then please contact our Excel Expert here .

Источник

VBA Cell Value – Get, Set, or Change

In this Article

This tutorial will teach you how to interact with Cell Values using VBA.

Set Cell Value

To set a Cell Value, use the Value property of the Range or Cells object.

Range.Value & Cells.Value

There are two ways to reference cell(s) in VBA:

  • Range Object – Range(“A2”).Value
  • Cells Object – Cells(2,1).Value

The Range object allows you to reference a cell using the standard “A1” notation.

This will set the range A2’s value = 1:

The Cells object allows you to reference a cell by it’s row number and column number.

This will set range A2’s value = 1:

Notice that you enter the row number first:

Set Multiple Cells’ Values at Once

Instead of referencing a single cell, you can reference a range of cells and change all of the cell values at once:

Set Cell Value – Text

In the above examples, we set the cell value equal to a number (1). Instead, you can set the cell value equal to a string of text. In VBA, all text must be surrounded by quotations:

If you don’t surround the text with quotations, VBA will think you referencing a variable…

Set Cell Value – Variable

You can also set a cell value equal to a variable

Get Cell Value

You can get cell values using the same Value property that we used above.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

Get ActiveCell Value

To get the ActiveCell value and display it in a message box:

Assign Cell Value to Variable

To get a cell value and assign it to a variable:

Here we used a variable of type Variant. Variant variables can accept any type of values. Instead, you could use a String variable type:

A String variable type will accept numerical values, but it will store the numbers as text.

If you know your cell value will be numerical, you could use a Double variable type (Double variables can store decimal values):

However, if you attempt to store a cell value containing text in a double variable, you will receive an type mismatch error:

Other Cell Value Examples

Copy Cell Value

It’s easy to set a cell value equal to another cell value (or “Copy” a cell value):

You can even do this with ranges of cells (the ranges must be the same size):

Compare Cell Values

You can compare cell values using the standard comparison operators.

Test if cell values are equal:

Will return TRUE if cell values are equal. Otherwise FALSE.

You can also create an If Statement to compare cell values:

You can compare text in the same way (Remember that VBA is Case Sensitive)

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

VBA Listbox – Selected Item

In this Article

This article will demonstrate how to work with the selected item in a List Box in Excel VBA.

List Boxes show a list of options to users, allowing them to select one or more of the items. They are largely used in VBA forms but can also be used within your Excel worksheet.

Create List Box in a VBA Form

To create a list box in a VBA form, we first need to create the UserForm.

Once you have created your form, select the List Box control in the toolbox and then drag to create a list box on your form.

Add Values to the List Box

In the Initialize event of the form, type the following code. The List Box will pick up values that are stored in a Range of Cells in your Excel Worksheet.

When we run the form, the list box will be shown as demonstrated in the image below:

Select Values from the List Box

By default, a single value can be selected in a List Box in a user form. However this can be amended by changing the Multi-Select property of the list box.

Click on the list box to select it, and then in the Properties window, change the Multi-Select Property from 0-frmMultiSelectSingle to 1-frmMultiSelectMulti.

Now when we run the form, we can select more than one option in the List Box.

If we change the option to be 2-frmMultiSelectExtended, it means that we can select one of the values, and then, holding down the SHIFT key, select another value further down the list, and all the items between the 2 values selected will also be selected.

Work with the Selected Values in VBA

Depending on the type of option we have used for the Multi-Select property in the List Box, there are a number of ways we can use the value or values selected in the list box in VBA Code.

Assigning the Value to a Variable

We can use the After_Update event of the list box to assign the value selected to a variable.

Firstly, let us create a module level variable at the top of the form module.

Underneath the words, Option Explicit, create the following string variable.

Once we have created this variable, we can double-click on the List box to go to the code behind the form, or we can click on the code button in the VBE Editor.

The Click Event of the list box will be automatically created. Select the After_Update Event form the list of Procedures available.

In the After_Update event, type the following code:

NOTE: You can delete the Click event as it is not required.

Now, if we run the form and click on the list box, the selected value will be store in the variable. To test this, we can put a BREAK point in the code.

Now when we run the form, if we click on the list box, the code will go into DEBUG mode and stop at our break point. If we then press F8 on the keyboard to move a step further in the code, the variable will be populated with the selected item in the list.

We can view this value by resting the mouse on the variable.

We can view the value in the Immediate Window.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

Use a Command Button to Return the Value to Excel

Firstly, we create a command button on the form in order to have an OK button to return the value or values selected in the list box to Excel.

Select the Command Button control, and then click and drag in your form to create the button.

In the Properties window, change the name of the button to cmdOK, and change the Caption and Accelerator of the button.

The purpose of the Accelerator is for the user to use the keyboard to activate the button, in this case Alt+O would activate the button.

For the command button to work, we need to add code behind it so that when the button is clicked, the code runs. This is called the Click event of the button.

To get to the click event, double-click on the button in the design view of the form. The click event will be automatically created as this is the event that is most commonly used for Command buttons.

Type the following code into the click event of the command button.

The code will pick up the variable we declared in the After_Update event of the ListBox and return the value to the Range in Excel.

Alternatively, we can pick up the value directly from the List Box without using a variable.

When we run the form, the selected value will be returned to Excel when we click the OK button.

Select Multiple Values

If we have set the multi-select property of the list box to 1 or 2 which allows us to select multiple values in the list, then the code to select these values is slightly different.

The After_Update event is no longer fired when selecting the values in the list box – we therefore cannot use this event.

We can still use the command button click event, but we need to loop through the values selected in the list box in order to return them to Excel.

In the command button Click event, type the following code.

Now when we run the form, only the values that are selected will be returned to the Excel sheet.

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

Get Cell Value in Excel VBA

Get Cell Value with Excel VBA

A cell is an individual cell and is also a part of a range. Technically, there are two methods to interact with a cell in VBA: the range method and the cell method. We can use the range method like range(“A2”). The value will give us the value of the A2 cell, or we can use the cell method as cells(2,1). The value will also give us the value of A2 cells.

Be it Excel or VBA, we all need to work with cells because it will store all the data in cells. So, it all boils down to how well we know about cells in VBA. So, if cells are such a crucial part of the VBA, then it is important to understand them well. So, if you are a starter regarding VBA cells, this article will guide you on how to get cell values in Excel VBA in detail.

First, we can reference or work with cells in VBA in two ways: using CELLS property Using CELLS Property Cells are cells of the worksheet, and in VBA, when we refer to cells as a range property, we refer to the same cells. In VBA concepts, cells are also the same, no different from normal excel cells. read more and RANGE object. Of course, why CELLS is a property and why RANGE is an object is a different analogy. Later in the article, we will get to that point.

Table of contents

You are free to use this image on your website, templates, etc., Please provide us with an attribution link How to Provide Attribution? Article Link to be Hyperlinked
For eg:
Source: Get Cell Value in Excel VBA (wallstreetmojo.com)

Examples of getting Cell Value in Excel VBA

Below are the examples of getting cell values in Excel VBA.

Example #1 – Using RANGE or CELLS Property

In cell A1 we have a value of “India.”

We can reference this cell with a CELLS property or RANGE object. Let us see both of them in detail.

Using Range Property

First, start the macro procedure.

Code:

Now open the RANGE object.

Code:

The first argument of this object is “Cell1,” which is the cell we are referring to. In this case, it is cell A1, so we need to supply the cell address in double quotes for the RANGE object.

Code:

Since only one cell refers to other parameters is irrelevant, close the bracket and put a dot to see the IntelliSense list.

As you can see above, the moment we put a dot, we can see all the available IntelliSense lists of properties and methods of range objects.

Since we are selecting the cell, we need to choose the “SELECT” method from the IntelliSense list.

Code:

Now, select the cell other than A1 and run the code.

It does not matter which cell you select when you run the code. It has chosen the mentioned cell, i.e., the A1 cell.

Using Cells Property

Similarly, we use the CELLS property now.

Code:

Unlike the RANGE object, we could directly supply the cell address. However, using this CELLS property, we cannot do that.

The first argument of this property is “Row Index,” i.e., which row we are referring to. Since we are selecting cell A1 we are referring to the first row, so mention 1.

The next argument is the “Column Index,” i.e., which column we refer to. For example, the A1 cell column is the first column, so enter 1.

Our code reads CELLS (1, 1) i.e. first row first column = A1.

Now, put a dot and see whether you get to see the IntelliSense list or not.

We cannot see any IntelliSense list with CELLS properties, so we must be sure what we are writing. Enter “Select” as the method.

Code:

This will also select cell A1.

Example #2 – Get Value from Cell in Excel VBA

Selecting is the first thing we have learned. Now, we will see how to get value from cells. Before we select the cell, we need to define the variable to store the value from the cell.

Code:

Now, mention the cell address using either the RANGE object or the CELLS property. Since you are a beginner, use the RANGE object only because we can see the IntelliSense list with the RANGE object.

For the defined variable, put an equal sign and mention the cell address.

Code:

Once again, put a dot to see the IntelliSense list.

From the VBA IntelliSense list, choose the “Value” property to get the value from the mentioned cell.

Code:

Now, the variable “CellValue” holds the value from cell A1. Show this variable value in the message box in VBA.

Code:

Run the code and see the result in a message box.

Since there is a value of “INDIA” in cell A1, the same thing also appeared in the message box. Like this, we can get the value of the cell by the VBA value VBA Value In VBA, the value property is usually used alongside the range method to assign a value to a range. It’s a VBA built-in expression that we can use with other functions. read more of the cell.

Example #3 – Get Value from One Cell to Another Cell

We know how to get value from the cell using VBA. Now, the question is how to insert a value into the cell. Let us take the same example only. For cell A1, we need to insert the value of “INDIA,” which we can do from the code below.

Code:

It will insert the value of “INDIA” to cell A1. Similarly, we can write the code below to get value from one cell to another.

Code:

Let me explain the code to you.

Things to Remember

  • Inserting value to cells and getting value from the cell requires the VBA “VALUE” property to be used.
  • We can select only one cell using the CELLS property but use the RANGE object. Likewise, we can select multiple cells.

Recommended Articles

This article has been a guide to Get Cell Value in Excel VBA. Here, we discuss the examples of getting cell values using a range of cell properties in Excel VBA and a downloadable Excel template. Below you can find some useful Excel VBA articles: –

Источник

In this Article

  • Create List Box in a VBA Form
    • Add Values to the List Box
  • Select Values from the List Box
  • Work with the Selected Values in VBA
    • Assigning the Value to a Variable
    • Use a Command Button to Return the Value to Excel
  • Select Multiple Values

This article will demonstrate how to work with the selected item in a List Box in Excel VBA.

List Boxes show a list of options to users, allowing them to select one or more of the items. They are largely used in VBA forms but can also be used within your Excel worksheet.

Create List Box in a VBA Form

To create a list box in a VBA form, we first need to create the UserForm.

Once you have created your form, select the List Box control in the toolbox and then drag to create a list box on your form.

VBAControls ListBox

Add Values to the List Box

In the Initialize event of the form, type the following code. The List Box will pick up values that are stored in a Range of Cells in your Excel Worksheet.

Private Sub UserForm_Initialize()
  Dim rng As Range
  For Each rng In Range("A1:A50")
    Me.lstState.AddItem rng.Value
  Next rng
End Sub

When we run the form, the list box will be shown as demonstrated in the image below:

VBAListBox ShowList

Select Values from the List Box

By default, a single value can be selected in a List Box in a user form.  However this can be amended by changing the Multi-Select property of the list box.

Click on the list box to select it, and then in the Properties window, change the Multi-Select Property from 0-frmMultiSelectSingle to 1-frmMultiSelectMulti.

VBAListBox MultiSelect

Now when we run the form, we can select more than one option in the List Box.

VBAListBox MultiSelected

If we change the option to be 2-frmMultiSelectExtended, it means that we can select one of the values, and then, holding down the SHIFT key, select another value further down the list, and all the items between the 2 values selected will also be selected.

VBAListBox MultiSelect Extended

Work with the Selected Values in VBA

Depending on the type of option we have used for the Multi-Select property in the List Box, there are a number of ways we can use the value or values selected in the list box in VBA Code.

Assigning the Value to a Variable

We can use the After_Update event of the list box to assign the value selected to a variable.

Firstly, let us create a module level variable at the top of the form module.

Underneath the words, Option Explicit, create the following string variable.

Dim strState as String.

Once we have created this variable, we  can double-click on the List box to go to the code behind the form, or we can click on the code button in the VBE Editor.

The Click Event of the list box will be automatically created.  Select the After_Update Event form the list of Procedures available.

VBAListBox Select After Update

In the After_Update event, type the following code:

Private Sub lstState_AfterUpdate()
  strState = Me.lstState
End Sub

NOTE:  You can delete the Click event as it is not required.

Now, if we run the form and click on the list box, the selected value will be store in the variable.  To test this, we can put a BREAK point in the code.

VBAListBox BreakPoint

Now when we run the form, if we click on the list box, the code will go into DEBUG mode and stop at our break point.  If we then press F8 on the keyboard to move  a step further in the code, the variable will be populated with the selected item in the list.

We can view this value by resting the mouse on the variable.

VBAListBox BreakVariable

OR

We can view the value in the Immediate Window.

VBAListBox ImmediateWindow

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

Use a Command Button to Return the Value to Excel

Firstly, we create a command button on the form in order to have an OK button to return the value or values selected in the list box to Excel.

Select the Command Button control, and then click and drag in your form to create the button.

VBAListBox Commandbutton

In the Properties window, change the name of the button to cmdOK, and change the Caption and Accelerator of the button.

VBAControls Button Properties

The purpose of the Accelerator is for the user to use the keyboard to activate the button, in this case Alt+O would activate the button.

VBAControls Button Accelerator

For the command button to work, we need to add code behind it so that when the button is clicked, the code runs. This is called the Click event of the button.

To get to the click event, double-click on the button in the design view of the form. The click event will be automatically created as this is the event that is most commonly used for Command buttons.

Type the following code into the click event of the command button.

Private Sub cmdOK_Click()
  Range("E1") = strState
End Sub

The code will pick up the variable we declared in the After_Update event of the ListBox and return the value to the Range in Excel.

Alternatively, we can pick up the value directly from the List Box without using a variable.

Private Sub cmdOK_Click()
  Range("E1") = me.lstState
End Sub

When we run the form, the selected value will be returned to Excel when we click the OK button.

VBAListBox OK

Select Multiple Values

If we have set the multi-select property of the list box to 1 or 2 which allows us to select multiple values in the list, then the code to select these values is slightly different.

The After_Update event is no longer fired when selecting the values in the list box – we therefore cannot use this event.

We can still use the command button click event, but we need to loop through the values selected in the list box in order to return them to Excel.

In the command button Click event, type the following code.

Private Sub cmdOK_Click()
  Dim x As Integer
  Range("E1").Select
  For x = 0 To Me.lstState.ListCount - 1
     If Me.lstState.Selected(x) = True Then
        ActiveCell = Me.lstState.List(x)
        ActiveCell.Offset(1, 0).Select
     End If
  Next x
End Sub

Now when we run the form, only the values that are selected will be returned to the Excel sheet.

VBAListBox_MultiSelect ReturnToExcel

There are three methods to read the selected values from a combobox in VBA. Please go through the following blog to know how you can do it.

Method 1:

Consider, we have a dropdown list having days mentioned in it. The value selected in the dropdown is ‘Sunday’. Now, we will try to read the selected value from the dropdown list using Excel VBA.

get combobox selected value 1

To read the selected day from the dropdown list into a variable, we can use the following snippet.

get combobox selected value 2

In the above code, we are creating an object reference for the dropdown “Drop Down 1”.

If you observe the code, we are using OLEFormat.Object.  OLEFormat property is used when we are working with shapes (ComboBox, ListBox and so on) , inline shapes, or fields to return the OLEFormat object.

ddval’ is the variable that stores the value of the selected dropdown.

dd.List(dd.ListIndex)

Here, List returns an item from List index. List index is an expression that returns index of the objects in the list.

get combobox selected value 3

As we can see from the image above the variable ‘ddval’ has value ‘Sunday’.

Method 2:

In this method we will use ‘ListFillRange’. This property ‘ListFillRange’ reads the contents of every cell in the range designated for the list and inserts the cell values into the list box. Before fetching the selected dropdown value, we have to assign the range of dropdown values to property ‘ListFillRange’

Say, if the list of options are in Column Q starting from Q1 to Q10, then we define the listfillrange for the dropdown.

dropdown_selected_value

Once the ListFillRange is assigned, the selected dropdown value is fetched as below. ‘ddval’ is the variable that stores the dropdown value from the dropdown list.

get combobox selected value 5

Method 3:

In this method, we will use cell link to read the dropdown value to the variable.

get combobox selected value 8

Based on the selection in the dropdown list the cell link value in ‘I1’ changes. The cell link value in ‘I1’ can be used to read the selected dropdown value.

 

Offset method:

Here, we use ‘ListFillRange’ to identify the range and assign its value to the ‘rr’ variable. ‘x’ is the variable used to find the offset row location.

Based on ‘x’ value and by using offset function, the value of the dropdownlist is found as below

get combobox selected value 6

We are taking the dropdown value into the ‘ddval’ variable as shown in the image below.

get combobox selected value 7

This is how we get combobox selected value in VBA. If you have any queries then please contact our Excel Expert here.

Skip to content

Excel VBA UserForm ComboBox

  • Excel VBA UserForm CheckBox

ComboBox is one of the UserForm control. You can select and drag drop control on the UserForm. This control is used to store and display list of items to a list. This can be used on the UserForm. Please find more details about ComboBox Control in the following chapter. You can see how to load items to a Combo Box, how to get the value of combo box items, etc..,

  • VBA ComboBox_Control on the UserForm
  • Add Dynamic ComboBox_Control on the UserForm Using VBA
  • Add Items to ComboBox_Control Using VBA
  • Clear Items from the ComboBox_Control Using VBA
  • Get the selected value of the ComboBox_Control using VBA
  • VBA ComboBox default values in Excel
  • Get the total count of ComboBox Items
  • More details dbout the ComboBox_Control

VBA ComboBox_Control on the UserForm

Please find more details about VBA ActiveX Combo Box Control and how we are adding it on the UserForm.

    1. Go To Developer Tab and then click Visual Basic from the Code or Press Alt+F11.
    2. Go To Insert Menu, Click UserForm. Please find the screenshot for the same.

Excel VBA UserForm CheckBox

    1. Drag a ComboBox on the Userform from the Toolbox. Please find the screenshot for the same.

Combo Box Excel ActiveX Control10

    1. Double Click on the UserForm, and select the Userform event as shown in the below screen shot.

Excel VBA ListBox ActiveX Control

    1. Now can see the following code in the module.
Private Sub UserForm_Initialize()

End Sub
    1. Now, add the following code to the in between procedure.

Code:

Private Sub UserForm_Initialize()
    ComboBox1.AddItem "MBA"
    ComboBox1.AddItem "MCA"
    ComboBox1.AddItem "MSC"
    ComboBox1.AddItem "MECS"
    ComboBox1.AddItem "CA"
End Sub
    1. Now, Press ‘F5’ to run the code. You can see the following Output. It is shown in the following Screen Shot.

Combo Box Excel VBA ActiveX Control2

Add dynamic ComboBox_Control on the UserForm using VBA

Please find the following steps and example code, it will show you how to add dynamic Combo Box control on the userform.

    1. Add command button on the userform from the toolbox.
    2. Right click on the command button, click properties
    3. Change the command button caption to ‘Create_ComboBox ’
    4. Double click on the command button
    5. Now, it shows following code.
Private Sub CommandButton1_Click()
 
End Sub
    1. Call the below procedure named ‘Add_Dynamic_ComboBox ’ and find the below procedure to run.
Private Sub CommandButton1_Click()
    Call Add_Dynamic_ComboBox 
End Sub

Procedure to call in the Command Button :

Sub Add_Dynamic_ComboBox()
      'Add Dynamic Combo Box and assign it to object 'CmbBx'
    Set CmbBx = UserForm3.Controls.Add("Forms.comboBox.1")
        
    'Combo Box Position
    CmbBx.Left = 20
    CmbBx.Top = 10
End Sub
    1. Now, click F5 to run the macro, click ‘Create_ComboBox ’ button to see the result.
    2. You can see the created dynamic combo box in the following screen shot.

output:

Combo Box Excel VBA ActiveX Control1

Add Items to ComboBox_Control using VBA

Please find the following code, it will show you how to add list items to Combo Box.

Private Sub Insert _Items _To_ComboBox ()
    ComboBox1.AddItem "Item 1"
    ComboBox1.AddItem "Item 2"
    ComboBox1.AddItem "Item 3"
    ComboBox1.AddItem "Item 4"
    ComboBox1.AddItem "Item 5"
End Sub

In the above code ComboBox1 is the name of the Combo Box. Where ‘additem’ is the property of Combo Box.

Clear Items from the ComboBox_Control using VBA

Please find the following code, it will show you how to clear the Combo Box items. The below code clears the ComboBox1 items on the UserForm1.

Sub Clr_CmbBx()
    UserForm3.ComboBox1.Clear
End Sub

Get the selected value of the ComboBox using VBA

Please find the below code to know how to get the selected value of the Combo Box using VBA. In the below example value is the property of Combo box.

Sub Chk_Item_SelectOrNot()
    MsgBox ComboBox1.Value
End Sub

VBA ComboBox Default Values in Excel

Here is the VBA Combo Box default values in Excel. After adding items to Combo Box by using any of the below code you can define the default value.

Code 1:

The below code is useful to select blank option in Combo Box . Where ‘-1’ is the index number.

Sub LstBx_Dflt_Val_Ex1()
     UserForm3.ComboBox1.ListIndex = -1
End Sub

Code 2:

The below code is useful to select first item in the Combo Box from the available list. . Where ‘0’ is the index number.

Sub LstBx_Dflt_Val_Ex2()
     UserForm3.ComboBox1.ListIndex = 0
End Sub

Code 3:

The below code is useful to select second item in the Combo Box from the available list. Where ‘1’ is the index number.

Sub LstBx_Dflt_Val_Ex3()
     UserForm3.ComboBox1.ListIndex = 1
End Sub

Code 4:

The below code is useful to select the last item in the Combo Box from the available list. Where ‘1’ is the index number.

Sub LstBx_Dflt_Val_Ex4()
     UserForm3.ComboBox1.ListIndex = UserForm3.ComboBox 1.Count - 1
End Sub

Get the total count of ComboBox Items

Here is the following example, it will show you how to get the total count of items in a Combo Box. In the below example ComboBox1 is the Combo Box name and ListCount is the property of Combo Box .

Sub Get_Ttl_Cnt()
    MsgBox "Total Items in a ComboBox is " & UserForm3.ComboBox1.ListCount
End Sub

More Details About the ComboBox_Control

VBA ComboBox Excel Macros Examples Codes Adding Clearing Items

Please find more details about Remove Duplicates in Combo Box in Excel VBA.

Read More …

VBA Remove Duplicates in ComboBox

Please find the following link for more details about VBA Combo Box Excel Macros Examples and Codes Adding and Clearing Items.

Read More …

Excel VBA FAQs: Frequently Asked Questions

Please find the most frequently asked questions and answers for your reference. These are explained more detailed way with examples.

Read More …

Effortlessly Manage Your Projects and Resources
120+ Professional Project Management Templates!

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
Excel VBA Project Management Templates
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates

MS Word Pack
25+ Word PM Templates

Ultimate Project Management Template

Ultimate Resource Management Template

Project Portfolio Management Templates
      • In this topic:
  • VBA ComboBox_Control on the UserForm
  • Add dynamic ComboBox_Control on the UserForm using VBA
      • Procedure to call in the Command Button :
  • Add Items to ComboBox_Control using VBA
  • Clear Items from the ComboBox_Control using VBA
  • Get the selected value of the ComboBox using VBA
  • VBA ComboBox Default Values in Excel
      • Code 1:
      • Code 2:
      • Code 3:
      • Code 4:
  • Get the total count of ComboBox Items
  • More Details About the ComboBox_Control
      • VBA ComboBox Excel Macros Examples Codes Adding Clearing Items
      • VBA Remove Duplicates in ComboBox
      • Excel VBA FAQs: Frequently Asked Questions

VBA Reference

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:
By PNRaoLast Updated: March 2, 2023

Effectively Manage Your
Projects and  Resources

With Our Professional and Premium Project Management Templates!

ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.

We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.

Project Management
Excel VBA

Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.

Analysistabs Logo

Page load link

Go to Top

A cell is an individual cell and is also a part of a range. Technically, there are two methods to interact with a cell in VBA: the range method and the cell method. We can use the range method like range(“A2”). The value will give us the value of the A2 cell, or we can use the cell method as cells(2,1). The value will also give us the value of A2 cells.

Be it Excel or VBA, we all need to work with cells because it will store all the data in cells. So, it all boils down to how well we know about cells in VBA. So, if cells are such a crucial part of the VBA, then it is important to understand them well. So, if you are a starter regarding VBA cells, this article will guide you on how to get cell values in Excel VBA in detail.

First, we can reference or work with cells in VBA in two ways: using CELLS propertyCells are cells of the worksheet, and in VBA, when we refer to cells as a range property, we refer to the same cells. In VBA concepts, cells are also the same, no different from normal excel cells.read more and RANGE object. Of course, why CELLS is a property and why RANGE is an object is a different analogy. Later in the article, we will get to that point.

Table of contents
  • Get Cell Value with Excel VBA
    • Examples of getting Cell Value in Excel VBA
      • Example #1 – Using RANGE or CELLS Property
      • Example #2 – Get Value from Cell in Excel VBA
      • Example #3 – Get Value from One Cell to Another Cell
    • Things to Remember
    • Recommended Articles

Get-Cell-Value-in-VBA

Examples of getting Cell Value in Excel VBA

Below are the examples of getting cell values in Excel VBA.

You can download this VBA Get Cell Value Excel Template here – VBA Get Cell Value Excel Template

Example #1 – Using RANGE or CELLS Property

In cell A1 we have a value of “India.”

VBA Get cell value Example 1

We can reference this cell with a CELLS property or RANGE object. Let us see both of them in detail.

Using Range Property

First, start the macro procedure.

Code:

Sub Get_Cell_Value()

End Sub

VBA Get cell value Example 1-1

Now open the RANGE object.

Code:

Sub Get_Cell_Value()

Range(

End Sub

VBA Get cell value Example 1-2

The first argument of this object is “Cell1,” which is the cell we are referring to. In this case, it is cell A1, so we need to supply the cell address in double quotes for the RANGE object.

Code:

Sub Get_Cell_Value()

Range("A1")

End Sub

VBA Get cell value Example 1-3

Since only one cell refers to other parameters is irrelevant, close the bracket and put a dot to see the IntelliSense list.

VBA Get cell value Example 1-4

As you can see above, the moment we put a dot, we can see all the available IntelliSense lists of properties and methods of range objects.

Since we are selecting the cell, we need to choose the “SELECT” method from the IntelliSense list.

Code:

Sub Get_Cell_Value()

Range("A1").Select

End Sub

VBA Get cell value Example 1-5

Now, select the cell other than A1 and run the code.

vba get cell value example 1

It does not matter which cell you select when you run the code. It has chosen the mentioned cell, i.e., the A1 cell.

Using Cells Property

Similarly, we use the CELLS property now.

Code:

Sub Get_Cell_Value()

Range("A1").Select
Cells(

End Sub

Example 1-6

Unlike the RANGE object, we could directly supply the cell address. However, using this CELLS property, we cannot do that.

The first argument of this property is “Row Index,” i.e., which row we are referring to. Since we are selecting cell A1 we are referring to the first row, so mention 1.

Example 1-7

The next argument is the “Column Index,” i.e., which column we refer to. For example, the A1 cell column is the first column, so enter 1.

Example 1-8

Our code reads CELLS (1, 1) i.e. first row first column = A1.

Now, put a dot and see whether you get to see the IntelliSense list or not.

VBA Get cell value Example 1-9

We cannot see any IntelliSense list with CELLS properties, so we must be sure what we are writing. Enter “Select” as the method.

Code:

Sub Get_Cell_Value()

Range("A1").Select
Cells(1, 1).Select

End Sub

VBA Get cell value Example 1-10

This will also select cell A1.

Example #2 – Get Value from Cell in Excel VBA

Selecting is the first thing we have learned. Now, we will see how to get value from cells. Before we select the cell, we need to define the variable to store the value from the cell.

Code:

Sub Get_Cell_Value1()

Dim CellValue As String

End Sub

Example 2

Now, mention the cell address using either the RANGE object or the CELLS property. Since you are a beginner, use the RANGE object only because we can see the IntelliSense list with the RANGE object.

For the defined variable, put an equal sign and mention the cell address.

Code:

Sub Get_Cell_Value1()

Dim CellValue As String

CellValue = Range("A1")

End Sub

Example 2-1

Once again, put a dot to see the IntelliSense list.

Intellisense list Example 2-2

From the VBA IntelliSense list, choose the “Value” property to get the value from the mentioned cell.

Code:

Sub Get_Cell_Value1()

Dim CellValue As String

CellValue = Range("A1").Value

End Sub

Example 2-3

Now, the variable “CellValue” holds the value from cell A1. Show this variable value in the message box in VBA.

Code:

Sub Get_Cell_Value1()

Dim CellValue As String

CellValue = Range("A1").Value

MsgBox CellValue

End Sub

Example 2-4

Run the code and see the result in a message box.

vba get cell value example 2

Since there is a value of “INDIA” in cell A1, the same thing also appeared in the message box. Like this, we can get the value of the cell by the VBA valueIn VBA, the value property is usually used alongside the range method to assign a value to a range. It’s a VBA built-in expression that we can use with other functions.read more of the cell.

Example #3 – Get Value from One Cell to Another Cell

We know how to get value from the cell using VBA. Now, the question is how to insert a value into the cell. Let us take the same example only. For cell A1, we need to insert the value of “INDIA,” which we can do from the code below.

Code:

Sub Get_Cell_Value2()

Range("A1").Value = "INDIA"

End Sub

VBA Get cell value Example 3

It will insert the value of “INDIA” to cell A1. Similarly, we can write the code below to get value from one cell to another.

Code:

Sub Get_Cell_Value2()

Range("A5").Value = Range("A1").Value

End Sub

VBA Get cell value Example 3-1

Let me explain the code to you.

For cell A5, we need the value from the cell A1 value; that’s all this code says. So, this will get the value from cell A1 to A5 using 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.

VBA Get cell value Example 3-2

Things to Remember

  • Inserting value to cells and getting value from the cell requires the VBA “VALUE” property to be used.
  • We can select only one cell using the CELLS property but use the RANGE object. Likewise, we can select multiple cells.

Recommended Articles

This article has been a guide to Get Cell Value in Excel VBA. Here, we discuss the examples of getting cell values using a range of cell properties in Excel VBA and a downloadable Excel template. Below you can find some useful Excel VBA articles: –

  • VBA Variable Range
  • Split String into Array in VBA
  • Range Cells in VBA
  • Active Cell in VBA

VBA Get Cell Value

Excel VBA Get Cell Value

In VBA there are different ways to apply the same logic to get the cell values and for this, we have a basic function called as CELLS where we can choose the coordinates to get the value stored in those cells or cell range. We all have used the method of selecting the range of using RANGE(“cell position”). VALUE. Similarly, we have other methods to get the value stored in different selected cells. Excel VBA Get Cell Value is one of the simplest and basic functions which all of us should know how to use it.

If we see the syntax, the CELLS function only requires the Row index and Column index coordinates where we just need to put the position of cells.

VBA Get Cell Value Syntax

Examples of Get Cell Value in VBA Excel

We will learn how to use a Get Cell Value in Excel by using the VBA Code with the help of given examples.

You can download this VBA Get Cell Value Excel Template here – VBA Get Cell Value Excel Template

Example #1

Let us consider a cell which is B2 with the cell content as “TEST” as shown below. For this, follow the below steps:

VBA Get Cell Value Example 0-1

Step 1: Insert a new module inside Visual Basic Editor (VBE). Click on Insert tab > select Module.

Insert Module

Step 2: Write the subprocedure of VBA Get Cell Value.

Code:

Sub VBA_GetCellValue1()

End Sub

VBA Get Cell Value Example 1-1

Step 3: Now directly use the message box and in the use CELLS with the coordinates as per B2 cell which comes at 2nd row and 2nd column.

Code:

Sub VBA_GetCellValue1()

MsgBox Cells(2, 2)

End Sub

VBA Get Cell Value Example 1-3

Step 4: Run the code by pressing F5 or Play Button is mentioned below the menu bar. We will see the message which will pick up the value from cell B2 as shown below.

VBA Get Cell Value Example 1-4

Example #2

Let us see another simple code to get the cell value. We will use the same cell B2 as used in example-1. In this example, we will see how to move the cursor to the required cell. For this, follow the below steps:

Step 1: For this again open a new module and write the subprocedure for VBA Get Cell Value.

Code:

Sub VBA_GetCellValue2()

End Sub

VBA Get Cell Value Example 2-1

Step 2: Now use Range along with Select function to move the cursor.

Code:

Sub VBA_GetCellValue2()

Range("B2").Select

End Sub

Range Example 2-2

Step 3: Now move cursor away from cell B2 and then run the code, we will see the cursor is now moved back to cell B2.

VBA Get Cell Value Example 0-1

Step 4: This is how we can select the cell with and without cell value. There is one more way to get this one. For this, we will be using CELLS function and putting the same coordinates as used in example-1. The same procedure could be done using the CELLS function.

Code:

Sub VBA_GetCellValue2()

Cells(2, 2).Select

End Sub

VBA Get Cell Value Example 2-4

Example #3

In this example, we will see how to get the cell value in a message using a different type of method. For this, follow the below steps:

Step 1: For this, again open Module and write the sub procedure.

Code:

Sub VBA_GetCellValue3()

End Sub

VBA Get Cell Value Example 3-1

Step 2: In the name of VBA Get Cell Value as shown below. And in that, first, define a variable as String using DIM.

Code:

Sub VBA_GetCellValue3()

Dim Value As String

End Sub

String Example 3-2

Step 3: Using the defined variable VALUE, choose the value from the range cell B2.

Code:

Sub VBA_GetCellValue3()

Dim Value As String
Value = Range("B2").Value

End Sub

VBA Get Cell Value Example 3-3

Step 4: Use the message box to see the value stored in cell B2.

Code:

Sub VBA_GetCellValue3()

Dim Value As String
Value = Range("B2").Value
MsgBox Value

End Sub

VBA Get Cell Value Example 3-4

Step 5: Once we Run the code by pressing F5 or Play Button is mention below the menu bar, we will get the message box with value as TEST which is at cell B2.

Message Box Example 3-4

Step 6: Similar code, can be used if we select the data type as VARIANT instead of STRING. Whereas VARIANT in VBA allows numbers and text both in it.

Code:

Sub VBA_GetCellValue3()

Dim Value As Variant
Value = Range("B2").Value
MsgBox Value

End Sub

Variant Example 3-5

Example #4

There is another way to use Get Cell Value in VBA which is also another simplest way. For this, follow the below steps:

Step 1: For this again open a new module and select the cell range from where we want to put. Let say we want to use the same cell range B2 which we have been using before examples.

Code:

Sub VBA_GetCellValue4()

Range("B2").Value

End Sub

VBA Get Cell Value Example 4-1

Step 2: Now in manner use the cell where we want to put the value. And we are considering the cell A1 here.

Code:

Sub VBA_GetCellValue4()

Range("B2").Value = Range("A1").Value

End Sub

Range Example 4-2

Step 3: Now run the code to see the output. The value from cell B2 will be moved to cell A1.

VBA Get Cell Value Example 4-3

Pros of VBA Get Cell Value

  • This is the basic operation where can easily get cell values from anywhere.
  • It is very easy to copy or move the cell value or cursor to any place we want.

Things to Remember

  • CELLS function is easy to implement by just putting the co-ordinates of ROW and COLUMN respectively.
  • VBA Get Cell Value helps us to choose the cell value or put the cursor to the desired position.
  • VBA Get Cell Value individually may not be much useful but we can use this operation with different types of code to get valuable results.
  • Once done with code, please save the code in Macro Enable excel format to avoid losing the code.
  • VBA Get Cell Value can be used with CELLS function and with RANGE function as well.

Recommended Articles

This is a guide to the VBA Get Cell Value. Here we discuss how to use Get Cell Value in excel VBA along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. How to Use VBA Login?
  2. VBA Month | Examples With Excel Template
  3. How to Use Create Object Function in VBA Excel?
  4. How to Use VBA IsError Function?

How to get data from a ListBox control and put it into a worksheet in Excel.

ef31ffec140344f83332bf3f16bf56f2.jpg

Sections:

Get Data from a Single Selection ListBox

Get Data from a Multiple Selection ListBox

Where to Put the Code

Notes

Get Data from a Single Selection ListBox

ListBox1.Text

ListBox1 is the name of the ListBox with the selection.

Here is an example of using this feature where you take the selection from the ListBox and place it in cell B2 in the worksheet.

'Get input from ListBox
ListBoxValue = ListBox1.Text
'Store input in the worksheet
Sheets("Sheet1").Range("B2").Value = ListBoxValue

This puts the selected item into the ListBoxValue variable, which is then used to input that value into cell B2 on the worksheet named «Sheet1».

Note: If the option to make multiple selections is enabled, the above method will not work, even if the user selects only 1 item from the list; in such cases, use the next method.

Get Data from a Multiple Selection ListBox

(To enable multiple ListBox selections, view this tutorial: Multiple Selections in a ListBox)

Getting data for multiple selections requires more effort that the example above because we have to actually loop through all of the items in the list in order to see which ones have been selected.

'Loop through every item in the ListBox
For i = 0 To ListBox1.ListCount - 1

    'Check if the item was selected.
    If ListBox1.Selected(i) Then

        'If here, means this item has been selected.

        'Show selected items in a message box.
        MsgBox ListBox1.List(i)

    End If

Next i

This is a For loop in VBA.

ListBox1 is the name of the ListBox.

i is the variable that is used to loop through the items in the ListBox. When referencing an item from within the loop, you use this variable. This is used in the next two explanations in order to get information about the items during the loop.

ListBox1.Selected(i) returns a True or False value that lets you know if the item in the list was selected or not. This is what is used in the IF statement part of the code.

ListBox1.List(i) is how you reference the item from the ListBox while you are looping through the items.

MsgBox ListBox1.List(i) is a simple way for you to see what items have been selected. This is used for illustrative purposes.

In the sample file for this tutorial another line of code is included that will put all of the selected items into Column B in the worksheet. That line of code looks like this (it also goes inside of the For loop):

Range("B" & Rows.Count).End(xlUp).Offset(1).Value = ListBox1.List(i)

Full Code to Put Values into the Worksheet

'Loop through every item in the ListBox
For i = 0 To ListBox1.ListCount - 1

    'Check if the item was selected.
    If ListBox1.Selected(i) Then

        'If here, means this item has been selected.

        'Put all selected items in Column B
        Range("B" & Rows.Count).End(xlUp).Offset(1).Value = ListBox1.List(i)

        'Show selected items in a message box.
        'MsgBox ListBox1.List(i)

    End If

Next i

The message box code was commented-out but left in so it’s easier to see and understand.

Where to Put the Code

The above code, usually, should go inside of the code section for a command button; this allows something to happen with the ListBox selections after the user clicks a button.

In the examples for this tutorial, and the included file, this code is at the top of the section for the Store Input button, named CommandButton2.

You can get to this code section by double-clicking the Store Input button from the form in the VBA window (Alt + F11).

Notes

You don’t have to make two separate code sections for a ListBox to check if it allows for sinlge or multi-selections. You can always use the loop in the second section above and it will work in all cases.

The method for doing something with multiple selections can seem a little tricky, but you only really have to change the name of the ListBox to the name of the one you use and everything should work.

In the attached file, the ListBox is set to allow multiple selections using the Ctrl and Shift keys. This is done with this line at the top of the UserForm_Initialize() event:

ListBox1.MultiSelect = fmMultiSelectExtended

Download the sample file for this tutorial to work with these examples in Excel.

Similar Content on TeachExcel

Getting Data from a UserForm

Tutorial: How to get data from a UserForm in Excel, including from: text inputs (TextBox), list boxe…

Multiple Selections in a ListBox

Tutorial: There are two different kinds of multiple item selections that you can have for a ListBox …

Get Data from the Worksheet into a Macro in Excel

Tutorial: Here, you’ll learn how to get information from the Excel worksheet into a macro so you can…

Macro to get Data from Another Workbook in Excel

Tutorial:
Macro to get data from a workbook, closed or open, over a network or locally on your comp…

Get Data from Separate Workbooks in Excel

Tutorial: How to get data from separate workbooks in Excel. This tutorial includes an example using …

Get Values from a Chart

Macro: This macro will pull the values from a chart in excel and list those values on another spr…

Subscribe for Weekly Tutorials

BONUS: subscribe now to download our Top Tutorials Ebook!

Свойство 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.


Like this post? Please share to your friends:
  • Excel vba get row from range
  • Excel vba get range names
  • Excel vba get all sheets
  • Excel vba listobject range
  • Excel vba function with no return value