How can I get a range of cells selected via user mouse input for further processing using VBA?
asked Nov 2, 2010 at 18:10
3
Selection
is its own object within VBA. It functions much like a Range
object.
Selection and Range do not share all the same properties and methods, though, so for ease of use it might make sense just to create a range and set it equal to the Selection, then you can deal with it programmatically like any other range.
Dim myRange as Range
Set myRange = Selection
For further reading, check out the MSDN article.
answered Nov 2, 2010 at 18:25
MichaelMichael
1,6362 gold badges16 silver badges21 bronze badges
1
You can loop through the Selection object to see what was selected. Here is a code snippet from Microsoft (http://msdn.microsoft.com/en-us/library/aa203726(office.11).aspx):
Sub Count_Selection()
Dim cell As Object
Dim count As Integer
count = 0
For Each cell In Selection
count = count + 1
Next cell
MsgBox count & " item(s) selected"
End Sub
answered Nov 2, 2010 at 18:19
Miyagi CoderMiyagi Coder
5,4444 gold badges33 silver badges42 bronze badges
5
This depends on what you mean by «get the range of selection». If you mean getting the range address (like «A1:B1») then use the Address property of Selection object — as Michael stated Selection object is much like a Range object, so most properties and methods works on it.
Sub test()
Dim myString As String
myString = Selection.Address
End Sub
answered Feb 4, 2015 at 10:57
Peter MajkoPeter Majko
1,22110 silver badges22 bronze badges
1
In this post you will learn about different ways to select all cells of a worksheet using VBA. When developing VBA macros you may need the VBA program to select all cells of a worksheet. For an example you might need to select all cells before printing the Excel sheet. There are many ways to select all cells of an Excel worksheet using VBA. In this lesson you will learn four different ways to select all cells of an Excel sheet.
Table of contents
Select all cells using Cells.Select Method
Select all cells using UsedRange property
Select all cells using last row and column numbers
Select all cells using CurrentRegion property
Cells.Select Method
This is the simplest way to select all the cells of an Excel worksheet using VBA. If you want to select all the cells of the activesheet then you can use the below code to do that.
Sub SelectAllCells_Method1_A()
ActiveSheet.Cells.Select
End Sub
However keep in mind that this method will select all cells of the worksheet including the empty cells.
Sometimes you may need to select all cells of a specific sheet of a workbook which contains multiple worksheets. Then you can refer to that specific sheet by its name. If the name of the sheet is “Data” then you can modify the above VBA macro as follows.
Sub SelectAllCells_Method1_B()
Dim WS As Worksheet
Set WS = Worksheets(«Data»)
WS.Activate
WS.Cells.Select
End Sub
Note that it is important to use the Worksheet.Activate method before selecting all cells. Because the VBA program can’t select cells of a worksheet which is not active. Program will throw an error if you try to select cells of a worksheet which is not active.
UsedRange Method
Above macros select all the cells of the worksheet. So VBA programs select cells even beyond the last row and column having data. But what if you want to select all the cells only inside the range you have used? For that you can use Worksheet.UsedRange property.
Sub SelectAllCells_Method2()
Dim WS As Worksheet
Set WS = Worksheets(«Data»)
WS.Activate
WS.UsedRange.Select
End Sub
Above VBA code will select all the cells inside the range you have used.
Select all cells using last row and column numbers
Also there is an alternative way to do this using VBA. First we can find the row number of the bottom most cell having data. Next we can find the column number of the rightmost cell having data. Then we can select the complete range from cell A1 to cell with those last row and column numbers using VBA. Here is how we can do it.
Sub SelectAllCells_Method3()
Dim WS As Worksheet
Dim WS_LastRow As Long
Dim WS_LastColumn As Long
Dim MyRange As Range
Set WS = Worksheets(«Data»)
WS_LastRow = WS.Cells.Find(«*», [A1], , , xlByRows, xlPrevious).Row
WS_LastColumn = WS.Cells.Find(«*», [A1], , , xlByColumns, xlPrevious).Column
Set MyRange = WS.Range(Cells(1, 1), Cells(WS_LastRow, WS_LastColumn))
WS.Activate
MyRange.Select
End Sub
There is one difference between those last two methods. If you use the last row and column numbers method, the range will be selected from cell A1. But if you use the UsedRange property then the range will be started from the first cell with the data. However you can also modify the last row and column numbers macro to get the same result as the Worksheet.UsedRange property method. But it will be a little more complicated.
Using CurrentRegion Property
We can also use the Range.CurrentRegion property to select all cells of an Excel worksheet. We can easily do that by making a slight change to the UsedRange method. Here is how we can select all cells using the CurrentRegion property.
Sub SelectAllCells_Method4()
Dim WS As Worksheet
Set WS = Worksheets(«Data»)
WS.Activate
WS.Range(«A1»).CurrentRegion.Select
End Sub
However there is one limitation in this method. If you have empty rows in your worksheet, then the VBA program will select cells only upto that row.
In this Article
- Select a Single Cell Using VBA
- Select a Range of Cells Using VBA
- Select a Range of Non-Contiguous Cells Using VBA
- Select All the Cells in a Worksheet
- Select a Row
- Select a Column
- Select the Last Non-Blank Cell in a Column
- Select the Last Non-Blank Cell in a Row
- Select the Current Region in VBA
- Select a Cell That is Relative To Another Cell
- Select a Named Range in Excel
- Selecting a Cell on Another Worksheet
- Manipulating the Selection Object in VBA
- Using the With…End With Construct
VBA allows you to select a cell, ranges of cells, or all the cells in the worksheet. You can manipulate the selected cell or range using the Selection Object.
Select a Single Cell Using VBA
You can select a cell in a worksheet using the Select method. The following code will select cell A2 in the ActiveWorksheet:
Range("A2").Select
Or
Cells(2, 1).Select
The result is:
Select a Range of Cells Using VBA
You can select a group of cells in a worksheet using the Select method and the Range object. The following code will select A1:C5:
Range("A1:C5").Select
Select a Range of Non-Contiguous Cells Using VBA
You can select cells or ranges that are not next to each other, by separating the cells or ranges using a comma in VBA. The following code will allow you to select cells A1, C1, and E1:
Range("A1, C1, E1").Select
You can also select sets of non-contiguous ranges in VBA. The following code will select A1:A9 and B11:B18:
Range("A1:A9, B11:B18").Select
Select All the Cells in a Worksheet
You can select all the cells in a worksheet using VBA. The following code will select all the cells in a worksheet.
Cells.Select
Select a Row
You can select a certain row in a worksheet using the Row object and the index number of the row you want to select. The following code will select the first row in your worksheet:
Rows(1).Select
Select a Column
You can select a certain column in a worksheet using the Column object and the index number of the column you want to select. The following code will select column C in your worksheet:
Columns(3).Select
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!
Learn More
Select the Last Non-Blank Cell in a Column
Let’s say you have data in cells A1, A2, A3 and A4 and you would like to select the last non-blank cell which would be cell A4 in the column. You can use VBA to do this and the Range.End method.
The Range.End Method can take four arguments namely: xlToLeft, xlToRight, xlUp and xlDown.
The following code will select the last non-blank cell which would be A4 in this case, if A1 is the active cell:
Range("A1").End(xlDown).Select
Select the Last Non-Blank Cell in a Row
Let’s say you have data in cells A1, B1, C1, D1, and E1 and you would like to select the last non-blank cell which would be cell E1 in the row. You can use VBA to do this and the Range.End method.
The following code will select the last non-blank cell which would be E1 in this case, if A1 is the active cell:
Range("A1").End(xlToRight).Select
Select the Current Region in VBA
You can use the CurrentRegion Property of the Range Object in order to select a rectangular range of blank and non-blank cells around a specific given input cell. If you have data in cell A1, B1 and C1, the following code would select this region around cell A1:
Range("A1").CurrentRegion.Select
So the range A1:C1 would be selected.
VBA Programming | Code Generator does work for you!
Select a Cell That is Relative To Another Cell
You can use the Offset Property to select a cell that is relative to another cell. The following code shows you how to select cell B2 which is 1 row and 1 column relative to cell A1:
Range("A1").Offset(1, 1).Select
Select a Named Range in Excel
You can select Named Ranges as well. Let’s say you have named cells A1:A4 Fruit. You can use the following code to select this named range:
Range("Fruit").Select
Selecting a Cell on Another Worksheet
In order to select a cell on another worksheet, you first need to activate the sheet using the Worksheets.Activate method. The following code will allow you to select cell A7, on the sheet named Sheet5:
Worksheets("Sheet5").Activate
Range("A1").Select
Manipulating the Selection Object in VBA
Once you have selected a cell or range of cells, you can refer to the Selection Object in order to manipulate these cells. The following code selects the cells A1:C1 and sets the font of these cells to Arial, the font weight to bold, the font style to italics and the fill color to green.
Sub FormatSelection()
Range("A1:C1").Select
Selection.Font.Name = "Arial"
Selection.Font.Bold = True
Selection.Font.Italic = True
Selection.Interior.Color = vbGreen
End Sub
The result is:
Using the With…End With Construct
We can repeat the above example using the With / End With Statement to refer to the Selection Object only once. This saves typing and usually makes your code easier to read.
Sub UsingWithEndWithSelection()
Range("A1:C1").Select
With Selection
.Font.Name = "Arial"
.Font.Bold = True
.Font.Italic = True
.Interior.Color = vbGreen
End With
End Sub
Содержание
- How to select cells/ranges by using Visual Basic procedures in Excel
- How to Select a Cell on the Active Worksheet
- How to Select a Cell on Another Worksheet in the Same Workbook
- How to Select a Cell on a Worksheet in a Different Workbook
- How to Select a Range of Cells on the Active Worksheet
- How to Select a Range of Cells on Another Worksheet in the Same Workbook
- How to Select a Range of Cells on a Worksheet in a Different Workbook
- How to Select a Named Range on the Active Worksheet
- How to Select a Named Range on Another Worksheet in the Same Workbook
- How to Select a Named Range on a Worksheet in a Different Workbook
- How to Select a Cell Relative to the Active Cell
- How to Select a Cell Relative to Another (Not the Active) Cell
- How to Select a Range of Cells Offset from a Specified Range
- How to Select a Specified Range and Resize the Selection
- How to Select a Specified Range, Offset It, and Then Resize It
- How to Select the Union of Two or More Specified Ranges
- How to Select the Intersection of Two or More Specified Ranges
- How to Select the Last Cell of a Column of Contiguous Data
- How to Select the Blank Cell at Bottom of a Column of Contiguous Data
- How to Select an Entire Range of Contiguous Cells in a Column
- How to Select an Entire Range of Non-Contiguous Cells in a Column
- How to Select a Rectangular Range of Cells
- How to Select Multiple Non-Contiguous Columns of Varying Length
- Notes on the examples
- Свойство Worksheet.Cells (Excel)
- Синтаксис
- Замечания
- Пример
- Поддержка и обратная связь
- VBA Excel. Свойство Cells объекта Range
- Свойство Cells объекта Worksheet
- Свойство Cells объекта Range
- Обход диапазона ячеек циклом
- Обход ячеек циклом For Each… Next
- Обход диапазона циклом For… Next
- How to SELECT ALL the Cells in a Worksheet using a VBA Code
- VBA to Select All the Cells
- Notes
- The sheet Must Be Activated
- Worksheet.Cells property (Excel)
- Syntax
- Remarks
- Example
- Support and feedback
How to select cells/ranges by using Visual Basic procedures in Excel
Microsoft provides programming examples for illustration only, without warranty either expressed or implied. This includes, but is not limited to, the implied warranties of merchantability or fitness for a particular purpose. This article assumes that you are familiar with the programming language that is being demonstrated and with the tools that are used to create and to debug procedures. Microsoft support engineers can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific requirements. The examples in this article use the Visual Basic methods listed in the following table.
The examples in this article use the properties in the following table.
How to Select a Cell on the Active Worksheet
To select cell D5 on the active worksheet, you can use either of the following examples:
How to Select a Cell on Another Worksheet in the Same Workbook
To select cell E6 on another worksheet in the same workbook, you can use either of the following examples:
Or, you can activate the worksheet, and then use method 1 above to select the cell:
How to Select a Cell on a Worksheet in a Different Workbook
To select cell F7 on a worksheet in a different workbook, you can use either of the following examples:
Or, you can activate the worksheet, and then use method 1 above to select the cell:
How to Select a Range of Cells on the Active Worksheet
To select the range C2:D10 on the active worksheet, you can use any of the following examples:
How to Select a Range of Cells on Another Worksheet in the Same Workbook
To select the range D3:E11 on another worksheet in the same workbook, you can use either of the following examples:
Or, you can activate the worksheet, and then use method 4 above to select the range:
How to Select a Range of Cells on a Worksheet in a Different Workbook
To select the range E4:F12 on a worksheet in a different workbook, you can use either of the following examples:
Or, you can activate the worksheet, and then use method 4 above to select the range:
How to Select a Named Range on the Active Worksheet
To select the named range «Test» on the active worksheet, you can use either of the following examples:
How to Select a Named Range on Another Worksheet in the Same Workbook
To select the named range «Test» on another worksheet in the same workbook, you can use the following example:
Or, you can activate the worksheet, and then use method 7 above to select the named range:
How to Select a Named Range on a Worksheet in a Different Workbook
To select the named range «Test» on a worksheet in a different workbook, you can use the following example:
Or, you can activate the worksheet, and then use method 7 above to select the named range:
How to Select a Cell Relative to the Active Cell
To select a cell that is five rows below and four columns to the left of the active cell, you can use the following example:
To select a cell that is two rows above and three columns to the right of the active cell, you can use the following example:
An error will occur if you try to select a cell that is «off the worksheet.» The first example shown above will return an error if the active cell is in columns A through D, since moving four columns to the left would take the active cell to an invalid cell address.
How to Select a Cell Relative to Another (Not the Active) Cell
To select a cell that is five rows below and four columns to the right of cell C7, you can use either of the following examples:
How to Select a Range of Cells Offset from a Specified Range
To select a range of cells that is the same size as the named range «Test» but that is shifted four rows down and three columns to the right, you can use the following example:
If the named range is on another (not the active) worksheet, activate that worksheet first, and then select the range using the following example:
How to Select a Specified Range and Resize the Selection
To select the named range «Database» and then extend the selection by five rows, you can use the following example:
How to Select a Specified Range, Offset It, and Then Resize It
To select a range four rows below and three columns to the right of the named range «Database» and include two rows and one column more than the named range, you can use the following example:
How to Select the Union of Two or More Specified Ranges
To select the union (that is, the combined area) of the two named ranges «Test» and «Sample,» you can use the following example:
that both ranges must be on the same worksheet for this example to work. Note also that the Union method does not work across sheets. For example, this line works fine.
returns the error message:
Union method of application class failed
How to Select the Intersection of Two or More Specified Ranges
To select the intersection of the two named ranges «Test» and «Sample,» you can use the following example:
Note that both ranges must be on the same worksheet for this example to work.
Examples 17-21 in this article refer to the following sample set of data. Each example states the range of cells in the sample data that would be selected.
How to Select the Last Cell of a Column of Contiguous Data
To select the last cell in a contiguous column, use the following example:
When this code is used with the sample table, cell A4 will be selected.
How to Select the Blank Cell at Bottom of a Column of Contiguous Data
To select the cell below a range of contiguous cells, use the following example:
When this code is used with the sample table, cell A5 will be selected.
How to Select an Entire Range of Contiguous Cells in a Column
To select a range of contiguous cells in a column, use one of the following examples:
When this code is used with the sample table, cells A1 through A4 will be selected.
How to Select an Entire Range of Non-Contiguous Cells in a Column
To select a range of cells that are non-contiguous, use one of the following examples:
When this code is used with the sample table, it will select cells A1 through A6.
How to Select a Rectangular Range of Cells
In order to select a rectangular range of cells around a cell, use the CurrentRegion method. The range selected by the CurrentRegion method is an area bounded by any combination of blank rows and blank columns. The following is an example of how to use the CurrentRegion method:
This code will select cells A1 through C4. Other examples to select the same range of cells are listed below:
In some instances, you may want to select cells A1 through C6. In this example, the CurrentRegion method will not work because of the blank line on Row 5. The following examples will select all of the cells:
How to Select Multiple Non-Contiguous Columns of Varying Length
To select multiple non-contiguous columns of varying length, use the following sample table and macro example:
When this code is used with the sample table, cells A1:A3 and C1:C6 will be selected.
Notes on the examples
The ActiveSheet property can usually be omitted, because it is implied if a specific sheet is not named. For example, instead of
The ActiveWorkbook property can also usually be omitted. Unless a specific workbook is named, the active workbook is implied.
When you use the Application.Goto method, if you want to use two Cells methods within the Range method when the specified range is on another (not the active) worksheet, you must include the Sheets object each time. For example:
For any item in quotation marks (for example, the named range «Test»), you can also use a variable whose value is a text string. For example, instead of
Источник
Свойство Worksheet.Cells (Excel)
Возвращает объект Range , представляющий все ячейки на листе (а не только используемые в данный момент ячейки).
Синтаксис
выражение.Cells
Выражение Переменная, представляющая объект Worksheet .
Замечания
Так как элемент по умолчанию объекта Range направляет вызовы с параметрами в свойство Item, можно указать индекс строки и столбца сразу после ключевого слова Cells, вместо явного вызова свойства Item.
При использовании этого свойства без квалификатора объекта возвращается объект Range, который представляет все ячейки на активном листе.
Пример
В этом примере размер шрифта ячейки C5 на листе 1 активной книги устанавливается в 14 пунктов.
В этом примере формула очищается в ячейке 1 на листе 1 активной книги.
В этом примере шрифт и размер шрифта для каждой ячейки на листе Sheet1 устанавливается значение Arial из 8 точек.
В этом примере выполняется переключение сортировки между порядком по возрастанию и убыванию при двойном щелчке любой ячейки в диапазоне данных. Данные сортируются по столбцу ячейки, дважды щелкнув которую.
В этом примере выполняется просмотр столбца C активного листа, и для каждой ячейки с комментарием текст примечания помещается в столбец D и удаляется комментарий из столбца C.
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
VBA Excel. Свойство Cells объекта Range
Свойство Cells объекта Range в VBA Excel, представляющее коллекцию ячеек заданного диапазона. Обращение к ячейкам диапазона с помощью свойства Cells.
Свойство Cells объекта Worksheet
Обращение к ячейке «A1» активного рабочего листа с помощью свойства Cells:
В данном случае в качестве объекта Range выступает диапазон всего активного рабочего листа (ActiveSheet). Полный путь к ячейке «A1» можно записать так:
Обращение в VBA Excel к ячейке «C5» с помощью свойства Cells по имени рабочего листа (Worksheet) в другой книге Excel:
Обращение к диапазону «C5:G10» с помощью свойства Cells активного рабочего листа:
Свойство Cells объекта Range
Обращение в VBA Excel к ячейкам заданного диапазона с помощью свойства Cells рассмотрим на коллекции ячеек диапазона «C5:G10». Обращаться будем к ячейке «D8» активного листа:
Обратите внимание, что отсчет номеров строк, номеров и буквенных обозначений столбцов для указания адреса ячейки внутри диапазона ведется от верхней левой ячейки данного диапазона.
Обход диапазона ячеек циклом
Обход ячеек циклом For Each… Next
Обход ячеек циклом For Each… Next — это самый простой способ обхода всех ячеек заданного диапазона. Он может быть применен, например, для присвоения ячейкам свойств и значений или поиска ячейки с определенным свойством или значением.
Присвоение ячейкам диапазона «B3:F10» числовых значений, соответствующих их порядковым номерам (индексам) в диапазоне:
Поиск в диапазоне «B3:F10», заполненном предыдущим кодом VBA Excel значениями, ячейки со значением «27», окрашивание ее в зеленый цвет и выход из цикла:
Обход диапазона циклом For… Next
Цикл For… Next позволяет указывать переменные в качестве индексов ячеек или номеров строк и столбцов для обхода ячеек заданного диапазона.
Присвоение ячейкам диапазона «B3:F10» числовых значений, соответствующих их порядковым номерам (индексам) в диапазоне, с помощью цикла For… Next:
Если в блоке с оператором With вместо строки .Cells(i) = i указать строку без точки впереди — Cells(i) = i , то свойство Cells будет относиться не к диапазону Range(«B3:F10») , а к рабочему листу (объекту ActiveSheet). В этом случае, порядковыми номерами будут заполнены первые 40 ячеек первой строки активного рабочего листа.
Применение в качестве параметров свойства Cells объекта Range переменных, задающих номера строк и номера столбцов указанного диапазона при обходе его ячеек циклом For… Next:
Источник
How to SELECT ALL the Cells in a Worksheet using a VBA Code
In VBA, there is a property called CELLS that you can use to select all the cells that you have in a worksheet.
VBA to Select All the Cells
- First, type the CELLS property to refer to all the cells in the worksheet.
- After that, enter a (.) dot.
- At this point, you’ll have a list of methods and properties.
- From that list select “Select” or type “Select”.
Once you select the entire worksheet you can change the font, clear contents from it, or do other things.
Notes
- The CELLS property works just like the way you use the keyboard shortcut Control + A to select all the cells.
- When you run this VBA code, it will select all the cells even if the sheet is protected and some of the cells are locked.
- It will select cells that are hidden as well.
The sheet Must Be Activated
Now you need to understand one thing here when you select all the cells from a sheet that sheet needs to be activated. In short, you can’t select cells from a sheet that is not activated.
Let’s say you want to select all the cells from “Sheet1”. If you use the type below code, you’ll get an error. You need to activate the “Sheet1” first and then use the “Cells” property to select all the cells.
Now when you run this it will first activate the “Sheet1” and then select all the cells. This thing gives you a little limitation that you can’t select the entire sheet if that sheet is not activated.
Here’s another thing that you can do: You can add a new sheet and then select all the cells.
Источник
Worksheet.Cells property (Excel)
Returns a Range object that represents all the cells on the worksheet (not just the cells that are currently in use).
Syntax
expression.Cells
expression A variable that represents a Worksheet object.
Because the default member of Range forwards calls with parameters to the Item property, you can specify the row and column index immediately after the Cells keyword instead of an explicit call to Item.
Using this property without an object qualifier returns a Range object that represents all the cells on the active worksheet.
Example
This example sets the font size for cell C5 on Sheet1 of the active workbook to 14 points.
This example clears the formula in cell one on Sheet1 of the active workbook.
This example sets the font and font size for every cell on Sheet1 to 8-point Arial.
This example toggles a sort between ascending and descending order when you double-click any cell in the data range. The data is sorted based on the column of the cell that is double-clicked.
This example looks through column C of the active sheet, and for every cell that has a comment, it puts the comment text into column D and deletes the comment from column C.
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
Источник
Home / VBA / How to SELECT ALL the Cells in a Worksheet using a VBA Code
In VBA, there is a property called CELLS that you can use to select all the cells that you have in a worksheet.
Cells.Select
- First, type the CELLS property to refer to all the cells in the worksheet.
- After that, enter a (.) dot.
- At this point, you’ll have a list of methods and properties.
- From that list select “Select” or type “Select”.
Once you select the entire worksheet you can change the font, clear contents from it, or do other things.
Notes
- The CELLS property works just like the way you use the keyboard shortcut Control + A to select all the cells.
- When you run this VBA code, it will select all the cells even if the sheet is protected and some of the cells are locked.
- It will select cells that are hidden as well.
The sheet Must Be Activated
Now you need to understand one thing here when you select all the cells from a sheet that sheet needs to be activated. In short, you can’t select cells from a sheet that is not activated.
Let’s say you want to select all the cells from “Sheet1”. If you use the type below code, you’ll get an error. You need to activate the “Sheet1” first and then use the “Cells” property to select all the cells.
Worksheets("Sheet1").Activate
Cells.Select
Now when you run this it will first activate the “Sheet1” and then select all the cells. This thing gives you a little limitation that you can’t select the entire sheet if that sheet is not activated.
Here’s another thing that you can do: You can add a new sheet and then select all the cells.
Sheets.Add.Name = "mySheet"
Cells.Select
More Tutorials
- Count Rows using VBA in Excel
- Excel VBA Font (Color, Size, Type, and Bold)
- Excel VBA Hide and Unhide a Column or a Row
- Excel VBA Range – Working with Range and Cells in VBA
- Apply Borders on a Cell using VBA in Excel
- Find Last Row, Column, and Cell using VBA in Excel
- Insert a Row using VBA in Excel
- Merge Cells in Excel using a VBA Code
- Select a Range/Cell using VBA in Excel
- ActiveCell in VBA in Excel
- Special Cells Method in VBA in Excel
- UsedRange Property in VBA in Excel
- VBA AutoFit (Rows, Column, or the Entire Worksheet)
- VBA ClearContents (from a Cell, Range, or Entire Worksheet)
- VBA Copy Range to Another Sheet + Workbook
- VBA Enter Value in a Cell (Set, Get and Change)
- VBA Insert Column (Single and Multiple)
- VBA Named Range | (Static + from Selection + Dynamic)
- VBA Range Offset
- VBA Sort Range | (Descending, Multiple Columns, Sort Orientation
- VBA Wrap Text (Cell, Range, and Entire Worksheet)
- VBA Check IF a Cell is Empty + Multiple Cells
⇠ Back to What is VBA in Excel
Helpful Links – Developer Tab – Visual Basic Editor – Run a Macro – Personal Macro Workbook – Excel Macro Recorder – VBA Interview Questions – VBA Codes
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.
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.
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:
- Go to the Developer tab.
- Click on the Visual Basic option. This will open the VB editor in the backend.
- 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.
- Go to Insert and click on Module. This will insert a module object for your workbook.
- Copy and paste the code in the module window.
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).
After the basic stuff with VBA, it is important to understand how to work with a range of cells in the worksheet. Once you start executing the codes practically, you need to work with various cells. So, it is important to understand how to work with various cells. One such concept is VBA’s “Selection of Range.” This article will show you how to work with the “Selection Range” in Excel VBA.
Selection and Range are two different topics, but when we say to select the range or selection of range, it is a single concept. RANGE is an object, “Selection” is a property, and “Select” is a method. People tend to be confused about these terms. It is important to know the differences in general.
Table of contents
- Excel VBA Selection Range
- How to Select a Range in Excel VBA?
- Example #1
- Example #2 – Working with Current Selected Range
- Things to Remember Here
- Recommended Articles
- How to Select a Range in Excel VBA?
How to Select a Range in Excel VBA?
You can download this VBA Selection Range Excel Template here – VBA Selection Range Excel Template
Example #1
Assume you want to select cell A1 in the worksheet, then. But, first, we need to specify the cell address by using a RANGE object like below.
Code:
After mentioning the cell, we need to select and put a dot to see the IntelliSense list, which is associated with the RANGE object.
From this variety of lists, choose the “Select” method.
Code:
Sub Range_Example1() Range("A1").Select End Sub
Now, this code will select cell A1 in the active worksheet.
To select the cell in the different worksheets, specify the worksheet by its name. To specify the worksheet, we need to use the “WORKSHEET” object and enter the worksheet name in double quotes.
For example, if you want to select cell A1 in the worksheet “Data Sheet,” specify the worksheet just like below.
Code:
Sub Range_Example1() Worksheets ("Data Sheet") End Sub
Then continue the code to specify what we need to do in this sheet. For example, in “Data Sheet,” we need to select cell A1 so that the code will be RANGE(“A1”).Select.
Code:
Sub Range_Example1() Worksheets("Data Sheet").Range("A1").Select End Sub
When you try to execute this code, we will get the below error.
It is because “we cannot directly supply a range object and select method to the worksheets object.”
First, we need to select or activate the VBA worksheetWhen working with VBA, we frequently refer to or use the properties of another sheet. For instance, if we’re working on sheet 1 and need a value from cell A2 on sheet 2, we won’t be able to access it unless we first activate the sheet. So, to activate a sheet in VBA we use worksheet property as Worksheets(“Sheet2”). Activate.read more, and then we can do whatever we want.
Code:
Sub Range_Example1() Worksheets("Data Sheet").Activate Range("A1").Select End Sub
It will now select cell A1 in the worksheet “Data Sheet.”
Example #2 – Working with Current Selected Range
Selecting is different, and working with an already selected range of cells is different. For example, assume you want to insert a value “Hello VBA” to cell A1 then we can do it in two ways.
Firstly we can directly pass the VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more as RANGE(“A1”).Value = “Hello, VBA.”
Code:
Sub Range_Example1() Range("A1").Value = "Hello VBA" End Sub
This code will insert the value “Hello VBA” to cell A1, irrespective of which cell is currently selected.
Look at the above result of the code. When we execute this code, it has inserted the value “Hello VBA,” even though the currently selected cell is B2.
Secondly, we can insert the value into the cell using the “Selection” property. But, first, we need to select the cell manually and execute the code.
Code:
Sub Range_Example1() Selection.Value = "Hello VBA" End Sub
What this code will do is insert the value “Hello VBA” to the currently selected cell. For example, look at the below example of execution.
When we executed the code, my current selected cell was B2. Therefore, our code inserted the same value to the currently selected cell.
Now, we will select cell B3 and execute. There also, we will get the same value.
Another thing we can do with the “selection” property is insert a value to more than one cell. So, for example, we will select the range of cells from A1 to B5 now.
If we execute the code for all the selected cells, we get the value “Hello VBA.”
So, the simple difference between specifying a cell address by RANGE object and Selection property is that the Range object code will insert value to the cells specified explicitly.
But in the Selection object, it does not matter which cell you are in. It will insert the mentioned value to all the selected cells.
Things to Remember Here
- We cannot directly supply the select method under the Selection property.
- The RANGE is an object, and selection is property.
- Instead of range, we can use the CELLS property.
Recommended Articles
This article is a guide to VBA Selection Range. Here, we learn how to select a range in Excel VBA along with examples and download an Excel template. Below are some useful Excel articles related to VBA: –
- VBA DoEvents
- Range Cells in VBA
- VBA Intersect
- VBA Switch Function
Всё о работе с ячейками в Excel-VBA: обращение, перебор, удаление, вставка, скрытие, смена имени.
Содержание:
Table of Contents:
- Что такое ячейка Excel?
- Способы обращения к ячейкам
- Выбор и активация
- Получение и изменение значений ячеек
- Ячейки открытой книги
- Ячейки закрытой книги
- Перебор ячеек
- Перебор в произвольном диапазоне
- Свойства и методы ячеек
- Имя ячейки
- Адрес ячейки
- Размеры ячейки
- Запуск макроса активацией ячейки
2 нюанса:
- Я почти везде стараюсь использовать ThisWorkbook (а не, например, ActiveWorkbook) для обращения к текущей книге, в которой написан этот код (считаю это наиболее безопасным для новичков способом обращения к книгам, чтобы случайно не внести изменения в другие книги). Для экспериментов можете вставлять этот код в модули, коды книги, либо листа, и он будет работать только в пределах этой книги.
- Я использую английский эксель и у меня по стандарту листы называются Sheet1, Sheet2 и т.д. Если вы работаете в русском экселе, то замените Thisworkbook.Sheets(«Sheet1») на Thisworkbook.Sheets(«Лист1»). Если этого не сделать, то вы получите ошибку в связи с тем, что пытаетесь обратиться к несуществующему объекту. Можно также заменить на Thisworkbook.Sheets(1), но это менее безопасно.
Что такое ячейка Excel?
В большинстве мест пишут: «элемент, образованный пересечением столбца и строки». Это определение полезно для людей, которые не знакомы с понятием «таблица». Для того, чтобы понять чем на самом деле является ячейка Excel, необходимо заглянуть в объектную модель Excel. При этом определения объектов «ряд», «столбец» и «ячейка» будут отличаться в зависимости от того, как мы работаем с файлом.
Объекты в Excel-VBA. Пока мы работаем в Excel без углубления в VBA определение ячейки как «пересечения» строк и столбцов нам вполне хватает, но если мы решаем как-то автоматизировать процесс в VBA, то о нём лучше забыть и просто воспринимать лист как «мешок» ячеек, с каждой из которых VBA позволяет работать как минимум тремя способами:
- по цифровым координатам (ряд, столбец),
- по адресам формата А1, B2 и т.д. (сценарий целесообразности данного способа обращения в VBA мне сложно представить)
- по уникальному имени (во втором и третьем вариантах мы будем иметь дело не совсем с ячейкой, а с объектом 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. На это есть две причины:
- Это лишь имитация действий пользователя, которая замедляет выполнение программы. Работать с объектами книги можно напрямую без использования методов Select и Activate.
- Это усложняет код и может приводить к неожиданным последствиям. Каждый раз перед использованием 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
Перебор ячеек
Перебор в произвольном диапазоне
Скачать файл со всеми примерами
Пройтись по всем ячейкам в нужном диапазоне можно разными способами. Основные:
- Цикл 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 по порядку по строкам слева направо и по столбцам — сверху вниз. Данный способ можно использовать для действий, в который вам не важны номера ячеек (закрашивание, изменение форматирования, пересчёт чего-то и т.д.).
- Ту же задачу можно решить с помощью двух вложенных циклов — внешний будет перебирать ряды, а вложенный — ячейки в рядах. Этот способ я использую чаще всего, потому что он позволяет получить больше контроля над исполнением: на каждой итерации цикла нам доступны координаты ячеек. Для перебора всех ячеек на листе этим методом потребуется найти последнюю заполненную ячейку. Пример кода:
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
- Если нужно перебрать все ячейки в выделенном диапазоне на активном листе, то код будет выглядеть так:
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
Данный метод подходит для интерактивных макросов, которые выполняют действия над выбранными пользователем областями.
- Перебор ячеек в ряду
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
- Перебор ячеек в столбце
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
One of the basic things you need to do in Excel VBA is to select a specific range to do something with it. This article will show you how to use Range, Cells, Offset and Resize to select a range in Excel VBA.
Select all the cells of a worksheet
Cells.Select
Select a cell
Cells(4, 5).Select
=
Range("E4").Select
It seems Range() is much easier to read and Cells() is easier to use inside a loop.
Select a set of contiguous cells
Range("C3:G8").Select
=
Range(Cells(3, 3), Cells(8, 7)).Select
=
Range("C3", "G8").Select
Select a set of non contiguous cells
Range("A2,A4,B5").Select
Select a set of non contiguous cells and a range
Range("A2,A4,B5:B8").Select
Select a named range
Range("MyRange").Select
=
Application.Goto "MyRange"
Select an entire row
Range("1:1").Select
Select an entire column
Range("A:A").Select
Select the last cell of a column of contiguous data
Range("A1").End(xlDown).Select
When this code is used with the following example table, cell A3 will be selected.
Select the blank cell at bottom of a column of contiguous data
Range("A1").End(xlDown).Offset(1,0).Select
When this code is used with the following example table, cell A4 will be selected.
Select an entire range of contiguous cells in a column
Range("A1", Range("A1").End(xlDown)).Select
When this code is used with the following example table, range A1:A3 will be selected.
Select an entire range of non-contiguous cells in a column
Range("A1", Range("A" & Rows.Count).End(xlUp)).Select
Note: This VBA code supports Excel 2003 to 2013.
When this code is used with the following example table, range A1:A8 will be selected.
Select a rectangular range of cells around a cell
Range("A1").CurrentRegion.Select
Select a cell relative to another cell
ActiveCell.Offset(5, 5).Select
Range("D3").Offset(5, -1).Select
Select a specified range, offset It, and then resize It
Range("A1").Offset(3, 2).Resize(3, 3).Select
When this code is used with the following example table, range C4:E6 will be selected.