Vba excel select cell value

VBA Select Cell

VBA Select Cell

MS Excel provides several VBA inbuilt functions one of them is the Select a Cell Function, which is used to select a cell from the worksheet. There are two methods to select a cell by the Cell another is the Range. It can be used as the as a part of the formula in the cell. A cell is a property in the VBA, but Range is the Object, so we can use a cell with the range but cannot use the range with the cell.

As an example, if the user wants to give a reference for A5 then he can give by two way one is select a cell by the Cell (5,4) another is the Range (“A5”).

The Syntax of the Select Cell Function:

SELECT CELL () – It will return the value of the cell which is given in the reference. There are two ways to select a cell.

Ex: Select Cell function –

ActiveSheet.Cells(5, 4). Select

OR

ActiveSheet.Range("D5"). Select

How to Select Cell in Excel VBA?

We will learn how to select a cell in Excel Using VBA code with few examples.

You can download this VBA Select Cell Excel Template here – VBA Select Cell Excel Template

VBA Select Cell – Example #1

How to use the basic VBA Select Cell Function in MS Excel.

A user wants to select a header cell which is C5 and User name(D5) in his workbook, after that print this name in the workbook which is given in the reference given cell is D5.

Let’s see how the Select Cell function can solve his problem. Follow the below steps to select a cell in excel VBA.

Step 1: Open the MS Excel, go to sheet1 where the user wants to select a cell and display the name of the user.

 VBA Select Cell Example 1-1

Step 2: Go to the Developer tab >> Click on the Visual Basic.

VBA Select Cell Example 1-2

Step 3: Create one Select Cell_Example1() micro.

Code:

Sub Select_Cell_Example1()

End Sub

VBA Select Cell Example 1-3

Step 4: Now activate sheet and select the user’s name cell by the Cells method.

Code:

Sub Select_Cell_Example1()

  Sheets("Sheet1").Activate
  Cells(5, 3).Select

End Sub

VBA Select Cell Example 1-4

Step 5: Now select the User name cell which is D5 by Range method.

Code:

Sub Select_Cell_Example1()

  Sheets("Sheet1").Activate
  Cells(5, 3).Select
  Range("D5").Select

End Sub

VBA Select Cell Example 1-5

Step 6: Now print the User name.            

Code:

Sub Select_Cell_Example1()

  Sheets("Sheet1").Activate
  Cells(5, 3).Select
  Range("D5").Select
  MsgBox "User's Name is " & Range("D5").Value

End Sub

VBA Select Cell Example 1-6

Step 7: Click on the F8 button to run step by step or just click on the F5 button.

Result of Example 1-7

Summary of Example #1:

As the user wants to select the cells and display the value in that cell. He can achieve his requirement by Select cells and range method. Same we can see in the result.

VBA Select Cell – Example #2

How to use the VBA Select Cell Function with the Range in the MS Excel.

A user wants to select the cell Delhi which is B7 as the first cell of a range. So, by default, there is a data range which is A1 to C13. But the user wants to create his own range and from where he wants to select the first cell.

Let’s see how the Select Cell function can solve his problem. Follow the below steps to select a cell in excel VBA.

Step 1: Open the MS Excel, go to sheet2 where the user wants to select a cell and display the name of the user.

VBA Select Cell Example 2-1

Step 2: Go to the developer tab >> Click on the Visual Basic.

Step 3: Create one Select Cell_Example2() micro and inside declare a string as the select_status.

Code:

Sub Select_Cell_Example2()

  Dim select_status As String

End Sub

VBA Select Cell Example 2-2

Step 4: Now activate sheet, define a range from B7 to c13 and select the first cell in that defined range.

Code:

Sub Select_Cell_Example2()

  Dim select_status As String
  Sheets("Sheet2").Activate
  select_status = Range("B7:C13").Cells(1, 1).Select

End Sub

VBA Select Cell Example 2-3

Step 5: Now print the status of selection if it is selected then it will be true otherwise false.

Code:

Sub Select_Cell_Example2()

  Dim select_status As String
  Sheets("Sheet2").Activate
  select_status = Range("B7:C13").Cells(1, 1).Select
  MsgBox "Selection Action True/False: " & select_status

End Sub

VBA Select Cell Example 2-4

Step 7: Click on the F8 button to run step by step or just click on the F5 button.

Result of Example 2-5

Summary of Example #2:

As the user wants to define their own range and from where he wants to select the first cell. He can achieve his requirement by Select cells and range method. Same we can see in the result. As we can see in the result selection happed on Delhi which is the first cell of defined range by the user.

VBA Select Cell – Example #3

How to use the VBA Select Cell Function with the loop in the MS Excel.

A user wants to calculate how many employees record he has in the employee details table.

Let’s see how the Select Cell function can solve his problem. Follow the below steps to select a cell in excel VBA.

Step 1: Open MS Excel, go to sheet3 where the user wants to select a cell and display the name of the user.

VBA Select Cell Example 3-1

Step 2: Go to the developer tab >> Click on the Visual Basic.

Step 3: Create one Select Cell_Example3() micro and inside declare an Integer as the i.

Code:

Sub Select_Cell_Example3()

  Dim i As Integer

End Sub

VBA Select Cell Example 3-2

Step 4: Now activate sheet and start a for loop to count the number of the employees.

Code:

Sub Select_Cell_Example3()

  Dim i As Integer
  Sheets("Sheet3").Activate
  For i = 1 To 12
  Cells(i + 1, 5).Value = i
  Next i

End Sub

Example 3-3

Step 5: Now print the Total employee records available in the table.

Code:

Sub Select_Cell_Example3()

  Dim i As Integer
  Sheets("Sheet3").Activate
  For i = 1 To 12
  Cells(i + 1, 5).Value = i
  Next i

MsgBox "Total employee records available in table is " & (i - 1)

End Sub

Example 3-4

Step 7: Click on the F8 button to run step by step or just click on the F5 button.

Result of Example 3-5

Summary of Example #3:

As the user wants to calculate the number of employee’s record available in the employee table. He can achieve his requirement by Select cells in the for-loop method. Same we can see in the result. As we can see in the result the Total employee records available in the table is 12.

Things to Remember

  • The defined range by the user is different from the regular range as we can see in Example #1.
  • A cell is a property in the VBA, but Range is the Object, so we can use a cell with the range but cannot use the range with the cell.
  • A user can pass the column alphabetic name also in cells like Cells (5,” F”) it is the same as the Cells (5, 6).
  • Selecting a cell is not mandatory to perform any action on it.
  • To activate a sheet a user can use sheet activate method as we have used in the above examples.

Recommended Articles

This has been a guide to VBA Select Cell. Here we discussed how to Select Cells in Excel using VBA along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA 1004 Error
  2. VBA Get Cell Value
  3. VBA Color Index
  4. VBA RGB

When working with Excel, most of your time is spent in the worksheet area – dealing with cells and ranges.

And if you want to automate your work in Excel using VBA, you need to know how to work with cells and ranges using VBA.

There are a lot of different things you can do with ranges in VBA (such as select, copy, move, edit, etc.).

So to cover this topic, I will break this tutorial into sections and show you how to work with cells and ranges in Excel VBA using examples.

Let’s get started.

All the codes I mention in this tutorial need to be placed in the VB Editor. Go to the ‘Where to Put the VBA Code‘ section to know how it works.

If you’re interested in learning VBA the easy way, check out my Online Excel VBA Training.

Selecting a Cell / Range in Excel using VBA

To work with cells and ranges in Excel using VBA, you don’t need to select it.

In most of the cases, you are better off not selecting cells or ranges (as we will see).

Despite that, it’s important you go through this section and understand how it works. This will be crucial in your VBA learning and a lot of concepts covered here will be used throughout this tutorial.

So let’s start with a very simple example.

Selecting a Single Cell Using VBA

If you want to select a single cell in the active sheet (say A1), then you can use the below code:

Sub SelectCell()
Range("A1").Select
End Sub

The above code has the mandatory ‘Sub’ and ‘End Sub’ part, and a line of code that selects cell A1.

Range(“A1”) tells VBA the address of the cell that we want to refer to.

Select is a method of the Range object and selects the cells/range specified in the Range object. The cell references need to be enclosed in double quotes.

This code would show an error in case a chart sheet is an active sheet. A chart sheet contains charts and is not widely used. Since it doesn’t have cells/ranges in it, the above code can’t select it and would end up showing an error.

Note that since you want to select the cell in the active sheet, you just need to specify the cell address.

But if you want to select the cell in another sheet (let’s say Sheet2), you need to first activate Sheet2 and then select the cell in it.

Sub SelectCell()
Worksheets("Sheet2").Activate
Range("A1").Select
End Sub

Similarly, you can also activate a workbook, then activate a specific worksheet in it, and then select a cell.

Sub SelectCell()
Workbooks("Book2.xlsx").Worksheets("Sheet2").Activate
Range("A1").Select
End Sub

Note that when you refer to workbooks, you need to use the full name along with the file extension (.xlsx in the above code). In case the workbook has never been saved, you don’t need to use the file extension.

Now, these examples are not very useful, but you will see later in this tutorial how we can use the same concepts to copy and paste cells in Excel (using VBA).

Just as we select a cell, we can also select a range.

In case of a range, it could be a fixed size range or a variable size range.

In a fixed size range, you would know how big the range is and you can use the exact size in your VBA code. But with a variable-sized range, you have no idea how big the range is and you need to use a little bit of VBA magic.

Let’s see how to do this.

Selecting a Fix Sized Range

Here is the code that will select the range A1:D20.

Sub SelectRange()
Range("A1:D20").Select
End Sub

Another way of doing this is using the below code:

Sub SelectRange()
Range("A1", "D20").Select
End Sub

The above code takes the top-left cell address (A1) and the bottom-right cell address (D20) and selects the entire range. This technique becomes useful when you’re working with variably sized ranges (as we will see when the End property is covered later in this tutorial).

If you want the selection to happen in a different workbook or a different worksheet, then you need to tell VBA the exact names of these objects.

For example, the below code would select the range A1:D20 in Sheet2 worksheet in the Book2 workbook.

Sub SelectRange()
Workbooks("Book2.xlsx").Worksheets("Sheet1").Activate
Range("A1:D20").Select
End Sub

Now, what if you don’t know how many rows are there. What if you want to select all the cells that have a value in it.

In these cases, you need to use the methods shown in the next section (on selecting variably sized range).

Selecting a Variably Sized Range

There are different ways you can select a range of cells. The method you choose would depend on how the data is structured.

In this section, I will cover some useful techniques that are really useful when you work with ranges in VBA.  

Select Using CurrentRange Property

In cases where you don’t know how many rows/columns have the data, you can use the CurrentRange property of the Range object.

The CurrentRange property covers all the contiguous filled cells in a data range.

Below is the code that will select the current region that holds cell A1.

Sub SelectCurrentRegion()
Range("A1").CurrentRegion.Select
End Sub

The above method is good when you have all data as a table without any blank rows/columns in it.

Cells and Ranges in VBA - currentregion property

But in case you have blank rows/columns in your data, it will not select the ones after the blank rows/columns. In the image below, the CurrentRegion code selects data till row 10 as row 11 is blank.

Cells and Ranges in VBA - currentregion property not selecting rows after blank

In such cases, you may want to use the UsedRange property of the Worksheet Object.

Select Using UsedRange Property

UsedRange allows you to refer to any cells that have been changed.

So the below code would select all the used cells in the active sheet.

Sub SelectUsedRegion()
ActiveSheet.UsedRange.Select
End Sub

Note that in case you have a far-off cell that has been used, it would be considered by the above code and all the cells till that used cell would be selected.

Select Using the End Property

Now, this part is really useful.

The End property allows you to select the last filled cell. This allows you to mimic the effect of Control Down/Up arrow key or Control Right/Left keys.

Let’s try and understand this using an example.

Suppose you have a dataset as shown below and you want to quickly select the last filled cells in column A.

The problem here is that data can change and you don’t know how many cells are filled. If you have to do this using keyboard, you can select cell A1, and then use Control + Down arrow key, and it will select the last filled cell in the column.

Now let’s see how to do this using VBA. This technique comes in handy when you want to quickly jump to the last filled cell in a variably-sized column

Sub GoToLastFilledCell()
Range("A1").End(xlDown).Select
End Sub

The above code would jump to the last filled cell in column A.

Similarly, you can use the End(xlToRight) to jump to the last filled cell in a row.

Sub GoToLastFilledCell()
Range("A1").End(xlToRight).Select
End Sub

Now, what if you want to select the entire column instead of jumping to the last filled cell.

You can do that using the code below:

Sub SelectFilledCells()
Range("A1", Range("A1").End(xlDown)).Select
End Sub

In the above code, we have used the first and the last reference of the cell that we need to select. No matter how many filled cells are there, the above code will select all.

Remember the example above where we selected the range A1:D20 by using the following line of code:

Range(“A1″,”D20”)

Here A1 was the top-left cell and D20 was the bottom-right cell in the range. We can use the same logic in selecting variably sized ranges. But since we don’t know the exact address of the bottom-right cell, we used the End property to get it.

In Range(“A1”, Range(“A1”).End(xlDown)), “A1” refers to the first cell and Range(“A1”).End(xlDown) refers to the last cell. Since we have provided both the references, the Select method selects all the cells between these two references.

Similarly, you can also select an entire data set that has multiple rows and columns.

The below code would select all the filled rows/columns starting from cell A1.

Sub SelectFilledCells()
Range("A1", Range("A1").End(xlDown).End(xlToRight)).Select
End Sub

In the above code, we have used Range(“A1”).End(xlDown).End(xlToRight) to get the reference of the bottom-right filled cell of the dataset.

Difference between Using CurrentRegion and End

If you’re wondering why use the End property to select the filled range when we have the CurrentRegion property, let me tell you the difference.

With End property, you can specify the start cell. For example, if you have your data in A1:D20, but the first row are headers, you can use the End property to select the data without the headers (using the code below).

Sub SelectFilledCells()
Range("A2", Range("A2").End(xlDown).End(xlToRight)).Select
End Sub

But the CurrentRegion would automatically select the entire dataset, including the headers.

So far in this tutorial, we have seen how to refer to a range of cells using different ways.

Now let’s see some ways where we can actually use these techniques to get some work done.

Copy Cells / Ranges Using VBA

As I mentioned at the beginning of this tutorial, selecting a cell is not necessary to perform actions on it. You will see in this section how to copy cells and ranges without even selecting these.

Let’s start with a simple example.

Copying Single Cell

If you want to copy cell A1 and paste it into cell D1, the below code would do it.

Sub CopyCell()
Range("A1").Copy Range("D1")
End Sub

Note that the copy method of the range object copies the cell (just like Control +C) and pastes it in the specified destination.

In the above example code, the destination is specified in the same line where you use the Copy method. If you want to make your code even more readable, you can use the below code:

Sub CopyCell()
Range("A1").Copy Destination:=Range("D1")
End Sub

The above codes will copy and paste the value as well as formatting/formulas in it.

As you might have already noticed, the above code copies the cell without selecting it. No matter where you’re on the worksheet, the code will copy cell A1 and paste it on D1.

Also, note that the above code would overwrite any existing code in cell D2. If you want Excel to let you know if there is already something in cell D1 without overwriting it, you can use the code below.

Sub CopyCell()
If Range("D1") <> "" Then
Response = MsgBox("Do you want to overwrite the existing data", vbYesNo)
End If
If Response = vbYes Then
Range("A1").Copy Range("D1")
End If
End Sub

Copying a Fix Sized Range

If you want to copy A1:D20 in J1:M20, you can use the below code:

Sub CopyRange()
Range("A1:D20").Copy Range("J1")
End Sub

In the destination cell, you just need to specify the address of the top-left cell. The code would automatically copy the exact copied range into the destination.

You can use the same construct to copy data from one sheet to the other.

The below code would copy A1:D20 from the active sheet to Sheet2.

Sub CopyRange()
Range("A1:D20").Copy Worksheets("Sheet2").Range("A1")
End Sub

The above copies the data from the active sheet. So make sure the sheet that has the data is the active sheet before running the code. To be safe, you can also specify the worksheet’s name while copying the data.

Sub CopyRange()
Worksheets("Sheet1").Range("A1:D20").Copy Worksheets("Sheet2").Range("A1")
End Sub

The good thing about the above code is that no matter which sheet is active, it will always copy the data from Sheet1 and paste it in Sheet2.

You can also copy a named range by using its name instead of the reference.

For example, if you have a named range called ‘SalesData’, you can use the below code to copy this data to Sheet2.

Sub CopyRange()
Range("SalesData").Copy Worksheets("Sheet2").Range("A1")
End Sub

If the scope of the named range is the entire workbook, you don’t need to be on the sheet that has the named range to run this code. Since the named range is scoped for the workbook, you can access it from any sheet using this code.

If you have a table with the name Table1, you can use the below code to copy it to Sheet2.

Sub CopyTable()
Range("Table1[#All]").Copy Worksheets("Sheet2").Range("A1")
End Sub

You can also copy a range to another Workbook.

In the following example, I copy the Excel table (Table1), into the Book2 workbook.

Sub CopyCurrentRegion()
Range("Table1[#All]").Copy Workbooks("Book2.xlsx").Worksheets("Sheet1").Range("A1")
End Sub

This code would work only if the Workbook is already open.

Copying a Variable Sized Range

One way to copy variable sized ranges is to convert these into named ranges or Excel Table and the use the codes as shown in the previous section.

But if you can’t do that, you can use the CurrentRegion or the End property of the range object.

The below code would copy the current region in the active sheet and paste it in Sheet2.

Sub CopyCurrentRegion()
Range("A1").CurrentRegion.Copy Worksheets("Sheet2").Range("A1")
End Sub

If you want to copy the first column of your data set till the last filled cell and paste it in Sheet2, you can use the below code:

Sub CopyCurrentRegion()
Range("A1", Range("A1").End(xlDown)).Copy Worksheets("Sheet2").Range("A1")
End Sub

If you want to copy the rows as well as columns, you can use the below code:

Sub CopyCurrentRegion()
Range("A1", Range("A1").End(xlDown).End(xlToRight)).Copy Worksheets("Sheet2").Range("A1")
End Sub

Note that all these codes don’t select the cells while getting executed. In general, you will find only a handful of cases where you actually need to select a cell/range before working on it.

Assigning Ranges to Object Variables

So far, we have been using the full address of the cells (such as Workbooks(“Book2.xlsx”).Worksheets(“Sheet1”).Range(“A1”)).

To make your code more manageable, you can assign these ranges to object variables and then use those variables.

For example, in the below code, I have assigned the source and destination range to object variables and then used these variables to copy data from one range to the other.

Sub CopyRange()
Dim SourceRange As Range
Dim DestinationRange As Range
Set SourceRange = Worksheets("Sheet1").Range("A1:D20")
Set DestinationRange = Worksheets("Sheet2").Range("A1")
SourceRange.Copy DestinationRange
End Sub

We start by declaring the variables as Range objects. Then we assign the range to these variables using the Set statement. Once the range has been assigned to the variable, you can simply use the variable.

Enter Data in the Next Empty Cell (Using Input Box)

You can use the Input boxes to allow the user to enter the data.

For example, suppose you have the data set below and you want to enter the sales record, you can use the input box in VBA. Using a code, we can make sure that it fills the data in the next blank row.

Sub EnterData()
Dim RefRange As Range
Set RefRange = Range("A1").End(xlDown).Offset(1, 0)
Set ProductCategory = RefRange.Offset(0, 1)
Set Quantity = RefRange.Offset(0, 2)
Set Amount = RefRange.Offset(0, 3)
RefRange.Value = RefRange.Offset(-1, 0).Value + 1
ProductCategory.Value = InputBox("Product Category")
Quantity.Value = InputBox("Quantity")
Amount.Value = InputBox("Amount")
End Sub

The above code uses the VBA Input box to get the inputs from the user, and then enters the inputs into the specified cells.

Note that we didn’t use exact cell references. Instead, we have used the End and Offset property to find the last empty cell and fill the data in it.

This code is far from usable. For example, if you enter a text string when the input box asks for quantity or amount, you will notice that Excel allows it. You can use an If condition to check whether the value is numeric or not and then allow it accordingly.

Looping Through Cells / Ranges

So far we can have seen how to select, copy, and enter the data in cells and ranges.

In this section, we will see how to loop through a set of cells/rows/columns in a range. This could be useful when you want to analyze each cell and perform some action based on it.

For example, if you want to highlight every third row in the selection, then you need to loop through and check for the row number. Similarly, if you want to highlight all the negative cells by changing the font color to red, you need to loop through and analyze each cell’s value.

Here is the code that will loop through the rows in the selected cells and highlight alternate rows.

Sub HighlightAlternateRows()
Dim Myrange As Range
Dim Myrow As Range
Set Myrange = Selection
For Each Myrow In Myrange.Rows
If Myrow.Row Mod 2 = 0 Then
Myrow.Interior.Color = vbCyan
End If
Next Myrow
End Sub

The above code uses the MOD function to check the row number in the selection. If the row number is even, it gets highlighted in cyan color.

Here is another example where the code goes through each cell and highlights the cells that have a negative value in it.

Sub HighlightAlternateRows()
Dim Myrange As Range
Dim Mycell As Range
Set Myrange = Selection
For Each Mycell In Myrange
If Mycell < 0 Then
Mycell.Interior.Color = vbRed
End If
Next Mycell
End Sub

Note that you can do the same thing using Conditional Formatting (which is dynamic and a better way to do this). This example is only for the purpose of showing you how looping works with cells and ranges in VBA.

Where to Put the VBA Code

Wondering where the VBA code goes in your Excel workbook?

Excel has a VBA backend called the VBA editor. You need to copy and paste the code in the VB Editor module code window.

Here are the steps to do this:

  1. Go to the Developer tab.vba cells and ranges - Developer Tab in ribbon
  2. Click on the Visual Basic option. This will open the VB editor in the backend.Click on Visual Basic
  3. In the Project Explorer pane in the VB Editor, right-click on any object for the workbook in which you want to insert the code. If you don’t see the Project Explorer, go to the View tab and click on Project Explorer.
  4. Go to Insert and click on Module. This will insert a module object for your workbook.Cells and Ranges in VBA - Module
  5. Copy and paste the code in the module window.Cells and Ranges in VBA - code paste

You May Also Like the Following Excel Tutorials:

  • Working with Worksheets using VBA.
  • Working with Workbooks using VBA.
  • Creating User-Defined Functions in Excel.
  • For Next Loop in Excel VBA – A Beginner’s Guide with Examples.
  • How to Use Excel VBA InStr Function (with practical EXAMPLES).
  • Excel VBA Msgbox.
  • How to Record a Macro in Excel.
  • How to Run a Macro in Excel.
  • How to Create an Add-in in Excel.
  • Excel Personal Macro Workbook | Save & Use Macros in All Workbooks.
  • Excel VBA Events – An Easy (and Complete) Guide.
  • Excel VBA Error Handling.
  • How to Sort Data in Excel using VBA (A Step-by-Step Guide).
  • 24 Useful Excel Macro Examples for VBA Beginners (Ready-to-use).

In VBA, the selection one may make by a keyword method statement known as a SELECT statement. The Select statement is used with the range property method to make any selection. We will still use the range property method with the select statement and the cell reference to select any particular cell.

In Excel, we work with cells and the range of the cell. In a regular worksheet, we can select the cell by mouse or reference the cellCell reference in excel is referring the other cells to a cell to use its values or properties. For instance, if we have data in cell A2 and want to use that in cell A1, use =A2 in cell A1, and this will copy the A2 value in A1.read more, as simple as that. However, in VBA, it is not that straightforward. For example, if we want to select the cell A1 using VBA, we cannot simply say “A1 cell”. Rather, we need to use the VBA RANGE objectRange 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 or CELLS property.

VBA codingVBA 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 is a language that specifies a way of doing tasks. For example, selecting cells in one of those tasks which we need to script in the VBA language. This article will show you how to select the cell using the VBA code.

Table of contents
  • Excel VBA Select Cell
    • How to Select Excel Cell using VBA?
      • Example #1 – Select Cell through Macro Recorder
      • Example #2 – Select Cells using Range Object
      • Example #3 – Insert Values to Cells
      • Example #4 – Select More than one Cell
      • Example #5 – Select cells by using CELLS Property
    • Recommended Articles

VBA Select Cell

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 Select Cell (wallstreetmojo.com)

How to Select Excel Cell using VBA?

You can download this VBA Select Cell Excel Template here – VBA Select Cell Excel Template

Example #1 – Select Cell through Macro Recorder

To start the learning, let us start the process by recording the macroRecording macros is a method whereby excel stores the tasks performed by the user. Every time a macro is run, these exact actions are performed automatically. Macros are created in either the View tab (under the “macros” drop-down) or the Developer tab of Excel.
read more
. But, first, place a cursor on a cell other than the A1 cell.

VBA Select cell Example 1

We have selected the B3 cell as of now.

Now click on the record macro buttonA Macro is nothing but a line of code to instruct the excel to do a specific task. Once the code is assigned to a button control through VBE you can execute the same task any time in the workbook. By just clicking on the button we can execute hundreds of line, it also automates the complicated Report.read more.

VBA Select cell Example 1-1

As soon as you click on that button, you will see a window. In this, you can give a new name or proceed with the default name by pressing the “OK” button.

VBA Select cell Example 1-2

Now, we are in the B3 cell, so select cell A1.

VBA Select cell Example 1-3

Now, stop the recording.

VBA Select cell Example 1-4

Click on “Visual Basic” to see what it has recorded.

VBA Select cell Example 1-5

Now, you will see the recording like this.

VBA Select cell Example 1-6

The only action we did while recording was to select cell A1. So, in VBA language, to select any cell, we need to use the RANGE object, then specify the cell name in double quotes and use the SELECT method to select the specified cell.

Example #2 – Select Cells using Range Object

By recording the Macro, we get to know how to select the cell. We need to use the object RANGE. Write on your own, type the word RANGE, and open parenthesis.

Code:

Sub Macro1()

Range(

End Sub

VBA Select cell Example 2

Now, it asks what the cell you want to refer to in the range, type “A1,” is. Then, enter the cell address, close the bracket, and type dot (.) to see all the properties and methods available with this cell.

VBA Select cell Example 2-1

Type SELECT as the method since we need to select the cell.

Code:

Sub Macro1()

Range("A1").Select

End Sub

VBA Select cell Example 2-2

Place a cursor in the different cells and run this code to see how it selects cell A1.

VBA Select cell Example 2-3

Example #3 – Insert Values to Cells

After selecting the cell, what do we usually do?

We perform some action. One action is to enter some value. We can enter the value in two ways. One is again using the RANGE object or uses the object ActiveCell,

To insert a value using the RANGE object, refer to cell A1 by using RANGE.

VBA Select cell Example 3

This time we are inserting the value, so select VALUE property.

Code:

Sub Macro1()

Range("A1").Select
Range("A1").Value

End Sub

VBA Select cell Example 3-1

To insert a value, put an equal sign and enter your value in double quotes if the value is text. If the value is numeric, you can directly enter the value.

Code:

Sub Macro1()

Range("A1").Select
Range("A1").Value = "Hello"

End Sub

Example 3-2

Now, press the F8 key to run the code line-by-line to understand the line of codes. For example, the first press of the F8 key will highlight the Macro name with yellow before this select B2 cell.

Upon pressing the F8 key one more time, it should insert the value “Hello” to cell A1.

Example 3-3

We can also insert the value by using the Active Cell method.

The moment we select the cell, it becomes an active cell. So, use the Property Active cell to insert the value.

Example 3-4

It is also the same as the last one. Using a range object makes it “explicit,” and using active cells makes it “Implicit.”

Example #4 – Select More than one Cell

We can also select multiple cells at a time. We need to specify the range of cells to select in double quotes. If you want to select cells from A1 to A5, below is the way.

Code:

Sub Macro2()

Range("A1:A5").Select

End Sub

Example 4

Run this code using the F5 key or manually to show the result.

Example 4-1

We can also select noncontiguous cells with a range object. So, for example, you can do this if you want to select cells from A1 to A5, C1 to C5, or E5 cells.

Code:

Sub Macro3()

Range("A1:A5,C1:C5,E5").Select

End Sub

Example 4-2

Run this code manually or through the F5 key to show the result.

Example 4-2

We need to start the double quote before we specify any cell and then close after the last cell.

Not only cells, but we can also select the named ranges by using the range’s name.

Example #5 – Select cells by using CELLS Property

Not through the RANGE object but also the CELLS property, we can select the cells.

VBA Cells

In the CELLS property, we need to specify the row and column numbers we select. Unlike a range method, we used A1, A5, C5, and C10 as references.

For example, CELLS (1,1) means A1 cell, and CELLS (2,5) means E2 cell. Like this, we can select the cells.

Code:

Sub Macro4()

Cells(2, 3).Select

End Sub

Example 4-3

Recommended Articles

This article has been a guide to VBA Select Cell. Here, we learn how to select an Excel cell using VBA code, practical examples, and a downloadable template. Below you can find some useful Excel VBA articles: –

  • VBA Range Cells
  • What are Clear Contents in Excel VBA?
  • Text Box in VBA
  • Do Until Loop in VBA

Всё о работе с ячейками в Excel-VBA: обращение, перебор, удаление, вставка, скрытие, смена имени.

Содержание:

Table of Contents:

  • Что такое ячейка Excel?
  • Способы обращения к ячейкам
    • Выбор и активация
    • Получение и изменение значений ячеек
      • Ячейки открытой книги
      • Ячейки закрытой книги 
    • Перебор ячеек
    • Перебор в произвольном диапазоне
  • Свойства и методы ячеек
    • Имя ячейки
    • Адрес ячейки
    • Размеры ячейки
  • Запуск макроса активацией ячейки

2 нюанса:

  1. Я почти везде стараюсь использовать ThisWorkbook (а не, например, ActiveWorkbook) для обращения к текущей книге, в которой написан этот код (считаю это наиболее безопасным для новичков способом обращения к книгам, чтобы случайно не внести изменения в другие книги). Для экспериментов можете вставлять этот код в модули, коды книги, либо листа, и он будет работать только в пределах этой книги. 
  2. Я использую английский эксель и у меня по стандарту листы называются Sheet1, Sheet2 и т.д. Если вы работаете в русском экселе, то замените Thisworkbook.Sheets(«Sheet1») на Thisworkbook.Sheets(«Лист1»). Если этого не сделать, то вы получите ошибку в связи с тем, что пытаетесь обратиться к несуществующему объекту. Можно также заменить на Thisworkbook.Sheets(1), но это менее безопасно.

Что такое ячейка Excel?

В большинстве мест пишут: «элемент, образованный пересечением столбца и строки». Это определение полезно для людей, которые не знакомы с понятием «таблица». Для того, чтобы понять чем на самом деле является ячейка Excel, необходимо заглянуть в объектную модель Excel. При этом определения объектов «ряд», «столбец» и «ячейка» будут отличаться в зависимости от того, как мы работаем с файлом.

Объекты в Excel-VBA. Пока мы работаем в Excel без углубления в VBA определение ячейки как «пересечения» строк и столбцов нам вполне хватает, но если мы решаем как-то автоматизировать процесс в VBA, то о нём лучше забыть и просто воспринимать лист как «мешок» ячеек, с каждой из которых VBA позволяет работать как минимум тремя способами:

  1. по цифровым координатам (ряд, столбец),
  2. по адресам формата А1, B2 и т.д. (сценарий целесообразности данного способа обращения в VBA мне сложно представить)
  3. по уникальному имени (во втором и третьем вариантах мы будем иметь дело не совсем с ячейкой, а с объектом VBA range, который может состоять из одной или нескольких ячеек). Функции и методы объектов Cells и Range отличаются. Новичкам я бы порекомендовал работать с ячейками VBA только с помощью Cells и по их цифровым координатам и использовать Range только по необходимости.

Все три способа обращения описаны далее

Как это хранится на диске и как с этим работать вне Excel? С точки зрения хранения и обработки вне Excel и VBA. Сделать это можно, например, сменив расширение файла с .xls(x) на .zip и открыв этот архив.

Пример содержимого файла Excel:

Далее xl -> worksheets и мы видим файл листа

Содержимое файла:

 То же, но более наглядно:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="x14ac xr xr2 xr3" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac" xmlns:xr="http://schemas.microsoft.com/office/spreadsheetml/2014/revision" xmlns:xr2="http://schemas.microsoft.com/office/spreadsheetml/2015/revision2" xmlns:xr3="http://schemas.microsoft.com/office/spreadsheetml/2016/revision3" xr:uid="{00000000-0001-0000-0000-000000000000}">
	<dimension ref="B2:F6"/>
	<sheetViews>
		<sheetView tabSelected="1" workbookViewId="0">
			<selection activeCell="D12" sqref="D12"/>
		</sheetView>
	</sheetViews>
	<sheetFormatPr defaultRowHeight="14.4" x14ac:dyDescent="0.3"/>
	<sheetData>
		<row r="2" spans="2:6" x14ac:dyDescent="0.3">
			<c r="B2" t="s">
				<v>0</v>
			</c>
		</row>
		<row r="3" spans="2:6" x14ac:dyDescent="0.3">
			<c r="C3" t="s">
				<v>1</v>
			</c>
		</row>
		<row r="4" spans="2:6" x14ac:dyDescent="0.3">
			<c r="D4" t="s">
				<v>2</v>
			</c>
		</row>
		<row r="5" spans="2:6" x14ac:dyDescent="0.3">
			<c r="E5" t="s">
				<v>0</v></c>
		</row>
		<row r="6" spans="2:6" x14ac:dyDescent="0.3">
			<c r="F6" t="s"><v>3</v>
		</c></row>
	</sheetData>
	<pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3"/>
</worksheet>

Как мы видим, в структуре объектной модели нет никаких «пересечений». Строго говоря рабочая книга — это архив структурированных данных в формате XML. При этом в каждую «строку» входит «столбец», и в нём в свою очередь прописан номер значения данного столбца, по которому оно подтягивается из другого XML файла при открытии книги для экономии места за счёт отсутствия повторяющихся значений. Почему это важно. Если мы захотим написать какой-то обработчик таких файлов, который будет напрямую редактировать данные в этих XML, то ориентироваться надо на такую модель и структуру данных. И правильное определение будет примерно таким: ячейка — это объект внутри столбца, который в свою очередь находится внутри строки в файле xml, в котором хранятся данные о содержимом листа.

Способы обращения к ячейкам

Выбор и активация

Почти во всех случаях можно и стоит избегать использования методов Select и Activate. На это есть две причины:

  1. Это лишь имитация действий пользователя, которая замедляет выполнение программы. Работать с объектами книги можно напрямую без использования методов Select и Activate.
  2. Это усложняет код и может приводить к неожиданным последствиям. Каждый раз перед использованием Select необходимо помнить, какие ещё объекты были выбраны до этого и не забывать при необходимости снимать выбор. Либо, например, в случае использования метода Select в самом начале программы может быть выбрано два листа вместо одного потому что пользователь запустил программу, выбрав другой лист.

Можно выбирать и активировать книги, листы, ячейки, фигуры, диаграммы, срезы, таблицы и т.д.

Отменить выбор  ячеек можно методом Unselect:

Selection.Unselect

Отличие выбора от активации — активировать можно только один объект из раннее выбранных. Выбрать можно несколько объектов.

Если вы записали и редактируете код макроса, то лучше всего заменить Select и Activate на конструкцию With … End With. Например, предположим, что мы записали вот такой макрос:

Sub Macro1()
' Macro1 Macro
    Range("F4:F10,H6:H10").Select 'выбрали два несмежных диапазона зажав ctrl
    Range("H6").Activate          'показывает только то, что я начал выбирать второй диапазон с этой ячейки (она осталась белой). Это действие ни на что не влияет
    With Selection.Interior       
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .Color = 65535            'залили желтым цветом, нажав на кнопку заливки на верхней панели
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With
End Sub

Почему макрос записался таким неэффективным образом? Потому что в каждый момент времени (в каждой строке) программа не знает, что вы будете делать дальше. Поэтому в записи выбор ячеек и действия с ними — это два отдельных действия. Этот код лучше всего оптимизировать (особенно если вы хотите скопировать его внутрь какого-нибудь цикла, который должен будет исполняться много раз и перебирать много объектов). Например, так:

Sub Macro11()
'
' Macro1 Macro
    Range("F4:F10,H6:H10").Select '1. смотрим, что за объект выбран (что идёт до .Select)
    Range("H6").Activate
    With Selection.Interior       '2. понимаем, что у выбранного объекта есть свойство interior, с которым далее идёт работа
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .Color = 65535
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With
End Sub



Sub Optimized_Macro()
    With Range("F4:F10,H6:H10").Interior '3. переносим объект напрямую в конструкцию With вместо Selection
' ////// Здесь я для надёжности прописал бы ещё Thisworkbook.Sheet("ИмяЛиста") перед Range,
' ////// чтобы минимизировать риск любых случайных изменений других листов и книг
' ////// With Thisworkbook.Sheet("ИмяЛиста").Range("F4:F10,H6:H10").Interior
        .Pattern = xlSolid               '4. полностью копируем всё, что было записано рекордером внутрь блока with
        .PatternColorIndex = xlAutomatic
        .Color = 55555                   '5. здесь я поменял цвет на зеленый, чтобы было видно, работает ли код при поочерёдном запуске двух макросов
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With
End Sub

Пример сценария, когда использование Select и Activate оправдано:

Допустим, мы хотим, чтобы во время исполнения программы мы одновременно изменяли несколько листов одним действием и пользователь видел какой-то определённый лист. Это можно сделать примерно так:

Sub Select_Activate_is_OK()
Thisworkbook.Worksheets(Array("Sheet1", "Sheet3")).Select 'Выбираем несколько листов по именам
Thisworkbook.Worksheets("Sheet3").Activate 'Показываем пользователю третий лист
'Далее все действия с выбранными ячейками через Select будут одновременно вносить изменения в оба выбранных листа

'Допустим, что тут мы решили покрасить те же два диапазона:
Range("F4:F10,H6:H10").Select
    Range("H6").Activate
    With Selection.Interior       
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .Color = 65535
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With

End Sub

Единственной причиной использовать этот код по моему мнению может быть желание зачем-то показать пользователю определённую страницу книги в какой-то момент исполнения программы. С точки зрения обработки объектов, опять же, эти действия лишние.

Получение и изменение значений ячеек

Значение ячеек можно получать/изменять с помощью свойства value. 

'Если нужно прочитать / записать значение ячейки, то используется свойство Value
a = ThisWorkbook.Sheets("Sheet1").Cells (1,1).Value 'записать значение ячейки А1 листа "Sheet1" в переменную "a"
ThisWorkbook.Sheets("Sheet1").Cells (1,1).Value = 1  'задать значение ячейки А1 (первый ряд, первый столбец) листа "Sheet1"

'Если нужно прочитать текст как есть (с форматированием), то можно использовать свойство .text:
ThisWorkbook.Sheets("Sheet1").Cells (1,1).Text = "1" 
a = ThisWorkbook.Sheets("Sheet1").Cells (1,1).Text

'Когда проявится разница:
'Например, если мы считываем дату в формате "31 декабря 2021 г.", хранящуюся как дата
a = ThisWorkbook.Sheets("Sheet1").Cells (1,1).Value 'эапишет как "31.12.2021"
a = ThisWorkbook.Sheets("Sheet1").Cells (1,1).Text  'запишет как "31 декабря 2021 г."

Ячейки открытой книги

К ячейкам можно обращаться:

'В книге, в которой хранится макрос (на каком-то из листов, либо в отдельном модуле или форме)
ThisWorkbook.Sheets("Sheet1").Cells(1,1).Value        'По номерам строки и столбца
ThisWorkbook.Sheets("Sheet1").Cells(1,"A").Value      'По номерам строки и букве столбца
ThisWorkbook.Sheets("Sheet1").Range("A1").Value       'По адресу - вариант 1
ThisWorkbook.Sheets("Sheet1").[A1].Value              'По адресу - вариант 2
ThisWorkbook.Sheets("Sheet1").Range("CellName").Value 'По имени ячейки (для этого ей предварительно нужно его присвоить)

'Те же действия, но с использованием полного названия рабочей книги (книга должна быть открыта)
Workbooks("workbook.xlsm").Sheets("Sheet1").Cells(1,1).Value 'По номерам строки и столбца
Workbooks("workbook.xlsm").Sheets("Sheet1").Cells(1,"A").Value                'По номерам строки и букве столбца
Workbooks("workbook.xlsm").Sheets("Sheet1").Range("A1").Value                 'По адресу - вариант 1
Workbooks("workbook.xlsm").Sheets("Sheet1").[A1].Value                        'По адресу - вариант 2
Workbooks("workbook.xlsm").Sheets("Sheet1").Range("CellName").Value           'По имени ячейки (для этого ей предварительно нужно его присвоить)

Ячейки закрытой книги

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

Workbooks.Open Filename:="С:closed_workbook.xlsx"    'открыть книгу (она становится активной)
a = ActiveWorkbook.Sheets("Sheet1").Cells(1,1).Value  'достать значение ячейки 1,1
ActiveWorkbook.Close False                            'закрыть книгу (False => без сохранения)

Скачать пример, в котором можно посмотреть, как доставать и как записывать значения в закрытую книгу. 

Код из файла:

Option Explicit
Sub get_value_from_closed_wb() 'достать значение из закрытой книги
Dim a, wb_path, wsh As String
wb_path = ThisWorkbook.Sheets("Sheet1").Cells(2, 3).Value 'get path to workbook from sheet1
wsh = ThisWorkbook.Sheets("Sheet1").Cells(3, 3).Value
Workbooks.Open Filename:=wb_path
a = ActiveWorkbook.Sheets(wsh).Cells(3, 3).Value
ActiveWorkbook.Close False
ThisWorkbook.Sheets("Sheet1").Cells(4, 3).Value = a
End Sub

Sub record_value_to_closed_wb() 'записать значение в закрытую книгу
Dim wb_path, b, wsh As String
wsh = ThisWorkbook.Sheets("Sheet1").Cells(3, 3).Value
wb_path = ThisWorkbook.Sheets("Sheet1").Cells(2, 3).Value 'get path to workbook from sheet1
b = ThisWorkbook.Sheets("Sheet1").Cells(5, 3).Value 'get value to record in the target workbook
Workbooks.Open Filename:=wb_path
ActiveWorkbook.Sheets(wsh).Cells(4, 4).Value = b 'add new value to cell D4 of the target workbook
ActiveWorkbook.Close True
End Sub

Перебор ячеек

Перебор в произвольном диапазоне

Скачать файл со всеми примерами

Пройтись по всем ячейкам в нужном диапазоне можно разными способами. Основные:

  1. Цикл For Each. Пример:
    Sub iterate_over_cells()
    
    For Each c In ThisWorkbook.Sheets("Sheet1").Range("B2:D4").Cells
    MsgBox (c)
    Next c
    
    End Sub​

    Этот цикл выведет в виде сообщений значения ячеек в диапазоне B2:D4 по порядку по строкам слева направо и по столбцам — сверху вниз. Данный способ можно использовать для действий, в который вам не важны номера ячеек (закрашивание, изменение форматирования, пересчёт чего-то и т.д.).

  2. Ту же задачу можно решить с помощью двух вложенных циклов — внешний будет перебирать ряды, а вложенный — ячейки в рядах. Этот способ я использую чаще всего, потому что он позволяет получить больше контроля над исполнением: на каждой итерации цикла нам доступны координаты ячеек. Для перебора всех ячеек на листе этим методом потребуется найти последнюю заполненную ячейку. Пример кода:
    Sub iterate_over_cells()
    
    Dim cl, rw As Integer
    Dim x As Variant
    
    'перебор области 3x3
    For rw = 1 To 3 ' цикл для перебора рядов 1-3
    
        For cl = 1 To 3 'цикл для перебора столбцов 1-3
            x = ThisWorkbook.Sheets("Sheet1").Cells(rw + 1, cl + 1).Value
            MsgBox (x)
        Next cl
    Next rw
    
    
    
    'перебор всех ячеек на листе. Последняя ячейка определена с помощью UsedRange
    'LastRow = ActiveSheet.UsedRange.Row + ActiveSheet.UsedRange.Rows.Count - 1
    'LastCol = ActiveSheet.UsedRange.Column + ActiveSheet.UsedRange.Columns.Count - 1
    'For rw = 1 To LastRow 'цикл перебора всех рядов
    '    For cl = 1 To LastCol 'цикл для перебора всех столбцов
    '        Действия 
    '    Next cl
    'Next rw
    
    
    End Sub​
  3. Если нужно перебрать все ячейки в выделенном диапазоне на активном листе, то код будет выглядеть так:
    Sub iterate_cell_by_cell_over_selection()
        Dim ActSheet As Worksheet
        Dim SelRange As Range
        Dim cell As Range
        
     
        Set ActSheet = ActiveSheet
        Set SelRange = Selection
        
        'if we want to do it in every cell of the selected range
        For Each cell In Selection
        MsgBox (cell.Value)
        
        Next cell
    
    End Sub​

    Данный метод подходит для интерактивных макросов, которые выполняют действия над выбранными пользователем областями.

  4. Перебор ячеек в ряду
    Sub iterate_cells_in_row()
        Dim i, RowNum, StartCell As Long
        
        RowNum = 3 'какой ряд
        StartCell = 0 ' номер начальной ячейки (минус 1, т.к. в цикле мы прибавляем i)
        
        For i = 1 To 10 ' 10 ячеек в выбранном ряду
        ThisWorkbook.Sheets("Sheet1").Cells(RowNum, i + StartCell).Value = i '(i + StartCell) добавляет 1 к номеру столбца при каждом повторении
        Next i
    
    End Sub
  5. Перебор ячеек в столбце
    Sub iterate_cells_in_column()
        Dim i, ColNum, StartCell As Long
        
        ColNum = 3 'какой столбец
        StartCell = 0 ' номер начальной ячейки (минус 1, т.к. в цикле мы прибавляем i)
        
        For i = 1 To 10 ' 10 ячеек
        ThisWorkbook.Sheets("Sheet1").Cells(i + StartCell, ColNum).Value = i ' (i + StartCell) добавляет 1 к номеру ряда при каждом повторении
        Next i
    
    End Sub​

Свойства и методы ячеек

Имя ячейки

Присвоить новое имя можно так:

Thisworkbook.Sheets(1).Cells(1,1).name = "Новое_Имя"

Для того, чтобы сменить имя ячейки нужно сначала удалить существующее имя, а затем присвоить новое. Удалить имя можно так:

ActiveWorkbook.Names("Старое_Имя").Delete

Пример кода для переименования ячеек:

Sub rename_cell()

old_name = "Cell_Old_Name"
new_name = "Cell_New_Name"

ActiveWorkbook.Names(old_name).Delete
ThisWorkbook.Sheets(1).Cells(2, 1).Name = new_name
End Sub

Sub rename_cell_reverse()

old_name = "Cell_New_Name"
new_name = "Cell_Old_Name"

ActiveWorkbook.Names(old_name).Delete
ThisWorkbook.Sheets(1).Cells(2, 1).Name = new_name
End Sub

Адрес ячейки

Sub get_cell_address() ' вывести адрес ячейки в формате буква столбца, номер ряда
  '$A$1 style
  txt_address = ThisWorkbook.Sheets(1).Cells(3, 2).Address
  MsgBox (txt_address)
End Sub

Sub get_cell_address_R1C1()' получить адрес столбца в формате номер ряда, номер столбца
  'R1C1 style
  txt_address = ThisWorkbook.Sheets(1).Cells(3, 2).Address(ReferenceStyle:=xlR1C1)
  MsgBox (txt_address)
End Sub

  'пример функции, которая принимает 2 аргумента: название именованного диапазона и тип желаемого адреса 
  '(1- тип $A$1 2- R1C1 - номер ряда, столбца)
Function get_cell_address_by_name(str As String, address_type As Integer)
  '$A$1 style
  Select Case address_type
    Case 1
      txt_address = Range(str).Address
    Case 2
      txt_address = Range(str).Address(ReferenceStyle:=xlR1C1)
    Case Else
      txt_address = "Wrong address type selected. 1,2 available"
    End Select
  get_cell_address_by_name = txt_address
End Function

'перед запуском нужно убедиться, что в книге есть диапазон с названием, 
'адрес которого мы хотим получить, иначе будет ошибка
Sub test_function() 'запустите эту программу, чтобы увидеть, как работает функция
  x = get_cell_address_by_name("MyValue", 2)
  MsgBox (x)
End Sub

Размеры ячейки

Ширина и длина ячейки в VBA меняется, например, так:

Sub change_size()
Dim x, y As Integer
Dim w, h As Double

'получить координаты целевой ячейки
x = ThisWorkbook.Sheets("Sheet1").Cells(2, 2).Value
y = ThisWorkbook.Sheets("Sheet1").Cells(3, 2).Value

'получить желаемую ширину и высоту ячейки
w = ThisWorkbook.Sheets("Sheet1").Cells(6, 2).Value
h = ThisWorkbook.Sheets("Sheet1").Cells(7, 2).Value

'сменить высоту и ширину ячейки с координатами x,y
ThisWorkbook.Sheets("Sheet1").Cells(x, y).RowHeight = h
ThisWorkbook.Sheets("Sheet1").Cells(x, y).ColumnWidth = w


End Sub

Прочитать значения ширины и высоты ячеек можно двумя способами (однако результаты будут в разных единицах измерения). Если написать просто Cells(x,y).Width или Cells(x,y).Height, то будет получен результат в pt (привязка к размеру шрифта). 

Sub get_size()
Dim x, y As Integer
'получить координаты ячейки, с которой мы будем работать
x = ThisWorkbook.Sheets("Sheet1").Cells(2, 2).Value
y = ThisWorkbook.Sheets("Sheet1").Cells(3, 2).Value

'получить длину и ширину выбранной ячейки в тех же единицах измерения, в которых мы их задавали
ThisWorkbook.Sheets("Sheet1").Cells(2, 6).Value = ThisWorkbook.Sheets("Sheet1").Cells(x, y).ColumnWidth
ThisWorkbook.Sheets("Sheet1").Cells(3, 6).Value = ThisWorkbook.Sheets("Sheet1").Cells(x, y).RowHeight

'получить длину и ширину с помощью свойств ячейки (только для чтения) в поинтах (pt)
ThisWorkbook.Sheets("Sheet1").Cells(7, 9).Value = ThisWorkbook.Sheets("Sheet1").Cells(x, y).Width
ThisWorkbook.Sheets("Sheet1").Cells(8, 9).Value = ThisWorkbook.Sheets("Sheet1").Cells(x, y).Height

End Sub

Скачать файл с примерами изменения и чтения размера ячеек

Запуск макроса активацией ячейки

Для запуска кода VBA при активации ячейки необходимо вставить в код листа нечто подобное:

3 важных момента, чтобы это работало:

1. Этот код должен быть вставлен в код листа (здесь контролируется диапазон D4)

2-3. Программа, ответственная за запуск кода при выборе ячейки, должна называться Worksheet_SelectionChange и должна принимать значение переменной Target, относящейся к триггеру SelectionChange. Другие доступные триггеры можно посмотреть в правом верхнем углу (2).

Скачать файл с базовым примером (как на картинке)

Скачать файл с расширенным примером (код ниже)

Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

        ' имеем в виду, что триггер SelectionChange будет запускать эту Sub после каждого клика мышью (после каждого клика будет проверяться:
          '1. количество выделенных ячеек и 
          '2. не пересекается ли выбранный диапазон с заданным в этой программе диапазоном.
        ' поэтому в эту программу не стоит без необходимости писать никаких других тяжелых операций

    If Selection.Count = 1 Then 'запускаем программу только если выбрано не более 1 ячейки


    'вариант модификации - брать адрес ячейки из другой ячейки:
    'Dim CellName as String
    'CellName = Activesheet.Cells(1,1).value 'брать текстовое имя контролируемой ячейки из A1 (должно быть в формате Буква столбца + номер строки)
    'If Not Intersect(Range(CellName), Target) Is Nothing Then
    'для работы этой модификации следующую строку надо закомментировать/удалить



        If Not Intersect(Range("D4"), Target) Is Nothing Then 
        'если заданный (D4) и выбранный диапазон пересекаются 
        '(пересечение диапазонов НЕ равно Nothing)

        'можно прописать диапазон из нескольких ячеек:
        'If Not Intersect(Range("D4:E10"), Target) Is Nothing Then
        'можно прописать несколько диапазонов:
        'If Not Intersect(Range("D4:E10"), Target) Is Nothing or Not Intersect(Range("A4:A10"), Target) Is Nothing Then

            Call program 'выполняем программу
        End If
    End If
End Sub

Sub program()

MsgBox ("Program Is running") 'здесь пишем код того, что произойдёт при выборе нужной ячейки


End Sub

Хитрости »

27 Июль 2013              307032 просмотров


Полагаю не совру когда скажу, что все кто программирует в VBA очень часто в своих кодах общаются к ячейкам листов. Ведь это чуть ли не основное предназначение VBA в Excel. В принципе ничего сложного в этом нет. Например, чтобы записать в ячейку A1 слово Привет необходимо выполнить код:

Range("A1").Value = "Привет"

Тоже самое можно сделать сразу для нескольких ячеек:

Range("A1:C10").Value = "Привет"

Если необходимо обратиться к именованному диапазону:

Range("Диапазон1").Select

Диапазон1 — это имя диапазона/ячейки, к которому надо обратиться в коде. Указывается в кавычках, как и адреса ячеек.
Но в VBA есть и альтернативный метод записи значений в ячейке — через объект Cells:

Cells(1, 1).Value = "Привет"

Синтаксис объекта Range:
Range(Cell1, Cell2)

  • Cell1 — первая ячейка диапазона. Может быть ссылкой на ячейку или диапазон ячеек, текстовым представлением адреса или имени диапазона/ячейки. Допускается указание несвязанных диапазонов(A1,B10), пересечений(A1 B10).
  • Cell2 — последняя ячейка диапазона. Необязательна к указанию. Допускается указание ссылки на ячейку, столбец или строку.

Синтаксис объекта Cells:
Cells(Rowindex, Columnindex)

  • Rowindex — номер строки
  • Columnindex — номер столбца

Исходя из этого несложно предположить, что к диапазону можно обратиться, используя Cells и Range:

'выделяем диапазон "A1:B10" на активном листе
Range(Cells(1,1), Cells(10,2)).Select

и для чего? Ведь можно гораздо короче:

Иногда обращение посредством Cells куда удобнее. Например для цикла по столбцам(да еще и с шагом 3) совершенно неудобно было бы использовать буквенное обозначение столбцов.
Объект Cells так же можно использовать для указания ячеек внутри непосредственно указанного диапазона. Например, Вам необходимо выделить ячейку в 3 строке и 2 столбце диапазона «D5:F56». Можно пройтись по листу и посмотреть, отсчитать нужное количество строк и столбцов и понять, что это будет «E7». А можно сделать проще:

Range("D5:F56").Cells(3, 2).Select

Согласитесь, это гораздо удобнее, чем отсчитывать каждый раз. Особенно, если придется оперировать смещением не на 2-3 ячейки, а на 20 и более. Конечно, можно было бы применить Offset. Но данное свойство именно смещает диапазон на указанное количество строк и столбцов и придется уменьшать на 1 смещение каждого параметра для получения нужной ячейки. Да и смещает на указанное количество строк и столбцов весь диапазон, а не одну ячейку. Это, конечно, тоже не проблема — можно вдобавок к этому использовать метод Resize — но запись получится несколько длиннее и менее наглядной:

Range("D5:F56").Offset(2, 1).Resize(1, 1).Select

И неплохо бы теперь понять, как значение диапазона присвоить переменной. Для начала переменная должна быть объявлена с типом Range. А т.к. Range относится к глобальному типу Object, то присвоение значения такой переменной должно быть обязательно с применением оператора Set:

Dim rR as Range
Set rR = Range("D5")

если оператор Set не применять, то в лучшем случае получите ошибку, а в худшем(он возможен, если переменной rR не назначать тип) переменной будет назначено значение Null или значение ячейки по умолчанию. Почему это хуже? Потому что в таком случае код продолжит выполняться, но логика кода будет неверной, т.к. эта самая переменная будет содержать значение неверного типа и применение её в коде в дальнейшем все равно приведет к ошибке. Только ошибку эту отловить будет уже сложнее.
Использовать же такую переменную в дальнейшем можно так же, как и прямое обращение к диапазону:

Вроде бы на этом можно было завершить, но…Это как раз только начало. То, что я написал выше знает практически каждый, кто пишет в VBA. Основной же целью этой статьи было пояснить некоторые нюансы обращения к диапазонам. Итак, поехали.

Обычно макрорекордер при обращении к диапазону(да и любым другим объектам) сначала его выделяет, а потом уже изменяет свойство или вызывает некий метод:

'так выглядит запись слова Test в ячейку А1
Range("A1").Select
Selection.Value = "Test"

Но как правило выделение — действие лишнее. Можно записать значение и без него:

'запишем слово Test в ячейку A1 на активном листе
Range("A1").Value = "Test"

Теперь чуть подробнее разберем, как обратиться к диапазону не выделяя его и при этом сделать все правильно. Диапазон и ячейка — это объекты листа. У каждого объекта есть родитель — грубо говоря это другой объект, который является управляющим для дочернего объекта. Для ячейки родительский объект — Лист, для Листа — Книга, для Книги — Приложение Excel. Если смотреть на иерархию зависимости объектов, то от старшего к младшему получится так:
Applicaton => Workbooks => Sheets => Range
По умолчанию для всех диапазонов и ячеек родительским объектом является текущий(активный) лист. Т.е. если для диапазона(ячейки) не указать явно лист, к которому он относится, в качестве родительского листа для него будет использован текущий — ActiveSheet:

'запишем слово Test в ячейку A1 на активном листе
Range("A1").Value = "Test"

Т.е. если в данный момент активен Лист1 — то слово Test будет записано в ячейку А1 Лист1. Если активен Лист3 — в А1 Лист3. Иначе говоря такая запись равносильна записи:

ActiveSheet.Range("A1").Value = "Test"

Поэтому выхода два — либо активировать сначала нужный лист, либо записать без активации.

'активируем Лист2
Worksheets("Лист2").Select
'записываем слово Test в ячейку A1
Range("A1").Value = "Test"

Чтобы не активируя другой лист записать в него данные, необходимо явно указать принадлежность объекта Range именно этому листу:

'запишем слово Test в ячейку A1 на Лист2 независимо от того, какой лист активен
Worksheets("Лист2").Range("A1").Value = "Test"

Таким же образом происходит считывание данных с ячеек — если не указывать лист, данные ячеек которого необходимо считать — считаны будут данные с ячейки активного листа. Чтобы считать данные с Лист2 независимо от того, какой лист активен применяется такой код:

'считываем значение ячейки A1 с Лист2 независимо от того, какой лист активен
MsgBox Worksheets("Лист2").Range("A1").Value

Т.к. ячейка является частью листа, то лист в свою очередь является частью книги. Исходя из того легко сделать вывод, что при открытых двух и более книгах мы так же можем обратиться к ячейкам любого листа любой открытой книги не активируя при этом ни книгу, ни лист:

'запишем слово Test в ячейку A1 на Лист2 книги Книга2.xlsx независимо от того, какая книга и какой лист активен
Workbooks("Книга2.xlsx").Worksheets("Лист2").Range("A1").Value = "Test"
'считываем значение ячейки A1 с Лист2 книги Книга3.xlsx независимо от того, какой лист активен
MsgBox Workbooks("Книга3.xlsx").Worksheets("Лист2").Range("A1").Value

Важный момент: лучше всегда указать имя книги вместе с расширением(.xlsx, xlsm, .xls и т.д.). Если в настройках ОС Windows(Панель управленияПараметры папок -вкладка ВидСкрывать расширения для зарегистрированных типов файлов) указано скрывать расширения — то указывать расширение не обязательно — Workbooks(«Книга2»). Но и ошибки не будет, если его указать. Однако, если пункт «Скрывать расширения для зарегистрированных типов файлов» отключен, то указание Workbooks(«Книга2») обязательно приведет к ошибке.


Очень часто ошибки обращения к ячейкам листов и книг делают начинающие, особенно в циклах по листам. Вот пример неправильного цикла:

Dim wsSh As Worksheet
For Each wsSh In ActiveWorkbook.Worksheets
    Range("A1").Value = wsSh.Name 'записываем в ячейку А1 имя листа
    MsgBox Range("A1").Value 'проверяем, то ли имя записалось
Next wsSh

MsgBox будет выдавать правильные значения, но сами имена листов будут записываться не на каждый лист, а последовательно в ячейку активного листа. Поэтому на активном листе в ячейке А1 будет имя последнего листа.
А вот так выглядит правильный цикл:
Вариант 1 — активация листа(медленный)

Dim wsSh As Worksheet
For Each wsSh In ActiveWorkbook.Worksheets
    wsSh.Activate 'активируем каждый лист
    Range("A1").Value = wsSh.Name 'записываем в ячейку А1 имя листа
    MsgBox Range("A1").Value 'проверяем, то ли имя записалось
Next wsSh

Вариант 2 — без активации листа(быстрый и более правильный)

Dim wsSh As Worksheet
For Each wsSh In ActiveWorkbook.Worksheets
    wsSh.Range("A1").Value = wsSh.Name 'записываем в ячейку А1 имя листа
    MsgBox wsSh.Range("A1").Value 'проверяем, то ли имя записалось
Next wsSh

Важно: если код записан в модуле листа(правая кнопка мыши на листе-Исходный текст) и для объекта Range или Cells родитель явно не указан(т.е. нет имени листа и книги) — тогда в качестве родителя будет использован именно тот лист, в котором записан код, независимо от того какой лист активный. Иными словами — если в модуле листа записать обращение вроде Range(«A1»).Value = «привет», то слово привет всегда будет записывать в ячейку A1 именно того листа, в котором записан сам код. Это следует учитывать, когда располагаете свои коды внутри модулей листов.

В конструкциях типа Range(Cells(,),Cells(,)) Range является контейнером, в котором указываются ссылки на объекты, из которых и будет создана ссылка на непосредственно конечный объект.
Предположим, что активен «Лист1», а код запущен с листа «Итог».
Если запись будет вида

Sheets("Итог").Range(Cells(1, 1), Cells(10, 1))

это вызовет ошибку «Run-time error ‘1004’: Application-defined or object-defined error». А ошибка появляется потому, что контейнер и объекты внутри него не могут располагаться на разных листах, равно как и:

Sheets("Итог").Range(Cells(1, 1), Sheets("Итог").Cells(10, 1))
'запись ниже так же неверна
Range(Cells(1, 1), Sheets("Итог").Cells(10, 1))

т.к. ссылки на объекты внутри контейнера относятся к разным листам. Cells(1, 1) — к активному листу, а Sheets(«Итог»).Cells(10, 1) — к листу Итог.
А вот такие записи будут правильными:

Sheets("Итог").Range(Sheets("Итог").Cells(1, 1), Sheets("Итог").Cells(10, 1))
Range(Sheets("Итог").Cells(1, 1), Sheets("Итог").Cells(10, 1))

Вторая запись не содержит ссылки на родителя для Range, но ошибки это в большинстве случаев не вызовет — т.к. если для контейнера ссылка не указана, а для двух объектов внутри контейнера родитель один — он будет применен и для самого контейнера. Однако лучше делать как в первой строке — т.е. с обязательным указанием родителя для контейнера и для его составляющих. Т.к. при определенных обстоятельствах(например, если в момент обращения к диапазону активной является книга, открытая в режиме защищенного просмотра) обращение к Range без родителя может вызывать ошибку выполнения.
Если запись будет вида Range(«A1″,»A10»), то указывать ссылку на родителя внутри Range не обязательно — достаточно будет указать эту ссылку перед самим Range — Sheets(«Итог»).Range(«A1″,»A10»), т.к. текстовое представление адреса внутри Range не является объектом(у которого может быть какой-то родительский объект), что обязывает создать ссылку именно на родителя контейнера.

Разберем пример, приближенный к жизненной ситуации. Необходимо на лист Итог занести формулу вычитания, начиная с ячейки А2 и до последней заполненной. На момент записи активен Лист1. Очень часто начинающие записывают так:

Sheets("Итог").Range("A2:A" & Cells(Rows.Count, 1).End(xlUp).Row) _
                                        .FormulaR1C1 = "=RC2-RC11"

Запись смешанная — и текстовое представление адреса ячейки(«A2:A») и ссылка на объект Cells. В данном случае явную ошибку код не вызовет, но и работать будет не всегда так, как хотелось бы. А это самое плохое, что может случиться при разработке.
Sheets(«Итог»).Range(«A2:A» — создается ссылка на столбец "A" листа Итог. Но далее идет вычисление последней строки первого столбца. И вот как раз это вычисление происходит на основе объекта Cells, который не содержит в себе ссылки на родительский объект. А значит он будет вычислять последнюю строку исключительно для текущего листа(если код записан в стандартном модуле, а не модуле листа) — т.е. для Лист1. Правильно было бы записать так:

Sheets("Итог").Range("A2:A" & Sheets("Итог").Cells(Rows.Count, 1).End(xlUp).Row) _
                                                      .FormulaR1C1 = "=RC2-RC11"

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

lLastRow = Workbooks("Книга3.xls").Sheets("Лист1").Cells(Rows.Count, 1).End(xlUp).Row

с виду все нормально, но есть нюанс. Rows.Count по умолчанию будет относится к активной книге, если записано в стандартном модуле. Приведенный выше код должен работать с книгой формата 97-2003 и вычислить последнюю заполненную ячейку на листе1. В книгах формата Excel 97-2003(.xls) всего 65536 строк. Если в момент выполнения приведенной строки активна книга формата 2007 и выше(форматы .xlsx, .xlsm, .xlsb и пр) — то Rows.Count вернет 1048576, т.к. именно такое количество строк в листах книг версий Excel, начиная с 2007. И т.к. в книге, в которой мы пытаемся вычислить последнюю строку всего 65536 строк — получим ошибку 1004, т.к. не может быть номера строки 1048576 на листе с количеством строк 65536. Поэтому имеет смысл указывать явно откуда считывать Rows.Count:

lLastRow = Workbooks("Книга3.xls").Sheets("Лист1").Cells(Workbooks("Книга3.xls").Sheets("Лист1").Rows.Count, 1).End(xlUp).Row

или применить конструкцию With

With Workbooks("Книга3.xls").Sheets("Лист1")
    lLastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
End With

Также не мешало бы упомянуть возможность выделения несмежного диапазона(часто его называют «рваным»). Это диапазон, который обычно привыкли выделять на листе при помощи зажатой клавиши Ctrl. Что это дает? Это дает возможность выделить одновременно ячейки A1 и B10 и записать значения только в них. Для этого есть несколько способов. Самый очевидный и описанный в справке — метод Union:

Union(Range("A1"), Range("B10")).Value = "Привет"

Однако существует и другой метод:

Range("A1,B10").Value = "Привет"

В чем отличие(я бы даже сказал преимущество) Union: можно применять в цикле по условию. Например, выделить в диапазоне A1:F50 только те ячейки, значение которых больше 10 и меньше 20:

Sub SelOne()
    Dim rCell As Range, rSel As Range
    For Each rCell In Range("A1:F50")
        If rCell.Value > 10 And rCell.Value < 20 Then
            If rSel Is Nothing Then
                Set rSel = rCell
            Else
                Set rSel = Union(rSel, rCell)
            End If
        End If
    Next rCell
    If Not rSel Is Nothing Then rSel.Select
End Sub

Конечно, можно и просто в Range через запятую передать все эти ячейки, сформировав предварительно строку. Но в случае со строкой действует ограничение: длина строки не должна превышать 255 символов.

Надеюсь, что после прочтения данной статьи проблем с обращением к диапазонам и ячейкам у Вас будет гораздо меньше.

Также см.:
Как определить последнюю ячейку на листе через VBA?
Как определить первую заполненную ячейку на листе?
Как из Excel обратиться к другому приложению


Статья помогла? Поделись ссылкой с друзьями!

  Плейлист   Видеоуроки


Поиск по меткам



Access
apple watch
Multex
Power Query и Power BI
VBA управление кодами
Бесплатные надстройки
Дата и время
Записки
ИП
Надстройки
Печать
Политика Конфиденциальности
Почта
Программы
Работа с приложениями
Разработка приложений
Росстат
Тренинги и вебинары
Финансовые
Форматирование
Функции Excel
акции MulTEx
ссылки
статистика

I need put data from selected cells to array. How to do it? I cant find any example. I know how to get value from one cell by ActiveCell.Value but how its work with multiple selection. Guess I should selected range put to variable as object and process it by foreach loop. Can anyone write example for it?

Solution:

Sub Button1_Click()

For Each OneCell In Selection
 MsgBox (OneCell.Value)
Next


End Sub

Community's user avatar

asked Dec 13, 2016 at 23:27

Yszty's user avatar

4

Application.Selection is not always Range (for example if Shape(s) or ActiveX Control(s) are selected), and Selection.Value returns different things depending on what is selected:

  • cell value if only one cell is selected
  • 2D Variant array of cell values if more than one cell is selected
  • error if the object(s) selected don’t have a .Value property

If more than one area is selected, .Value returns the value(s) only of the first area.


If TypeOf Selection Is Excel.Range Then
    Debug.Print Selection.Address(0, 0)

    For Each area In Selection.Areas
        Debug.Print area.Address(0, 0)
    Next
Else
    Debug.Print TypeName(Selection)
End If

The Locals window can make it easier to see the contents of the Application.Selection

answered Dec 14, 2016 at 1:46

Slai's user avatar

SlaiSlai

21.8k5 gold badges43 silver badges52 bronze badges

5

You don’t have to use OneCell.Value as the cell itself holds the value.
If you want to get the cells formula then use OneCell.FormulaR1C1.

    For Each OneCell In Selection
        MsgBox (OneCell)
    Next OneCell

answered Jan 19, 2018 at 6:42

Navin's user avatar

NavinNavin

2733 silver badges15 bronze badges

Понравилась статья? Поделить с друзьями:
  • Vba excel select case или
  • Vba excel select case and or
  • Vba excel select all in listbox
  • Vba excel saving a file
  • Vba excel saveas fileformat