Activate cells in excel

Home / VBA / How to use ActiveCell in VBA in Excel

In VBA, the active cell is a property that represents the cell that is active at the moment. When you select a cell or navigate to a cell and that green box covers that cell you can use ACTIVECELL property to refer to that cell in a VBA code. There are properties and methods that come with it.

Use the Active Cell Property

  1. Type the keyword “ActiveCell”.
  2. Type a dot (.) to get the list properties and methods.
  3. Select the property or method that you want to use.
  4. Run the code to perform the activity to the active cell.

Important Points

  • When you use the active cell property VBA refers to the active cell of the active workbook’s active sheet’s, irrespective of how many workbooks are open at the moment.
  • ActiveCell is ultimately a cell that comes with all the properties and methods that a normal cell comes with.

Activate a Cell from the Selected Range

To activate a cell using a VBA code there are two ways that you can use one “Activate” method and “Select” method.

Sub vba_activecell()

'select and entire range
Range("A1:A10").Select

'select the cell A3 from the selected range
Range("A3").Activate

'clears everything from the active cell
ActiveCell.Clear

End Sub

The above code, first of all, selects the range A1:A10 and then activates the cell A3 out of that and in the end, clears everything from the active cell i.e., A3.

Return Value from the Active Cell

The following code returns the value from the active cell using a message box.

MsgBox ActiveCell.Value

Or if you want to get the value from the active cell and paste it into a separate cell.

Range("A1") = ActiveCell.Value

Set Active Cell to a Variable

You can also set the active cell to the variable, just like the following example.

Sub vba_activecell()

'declares the variable as range
Dim myCell As Range

'set active cell to the variable
Set myCell = ActiveCell

'enter value in the active cell
myCell.Value = Done

End Sub

Get Row and Column Number of the ActiveCell

With the active cell there comes a row and column property that you can use to get the row and column number of the active cell.

MsgBox ActiveCell.Row

MsgBox ActiveCell.Column

Get Active Cell’s Address

You can use the address property to get the address of the active cell.

MsgBox ActiveCell.Address

When you run the above code, it shows you a message box with the cell address of the active cell of the active workbook’s active sheet (as I mentioned earlier).

Move from the Active Cell using Offset

With offset property, you can move to a cell which is a several rows and columns away from the active cell.

ActiveCell.Offset(2, 2).Select

Select a Range from the Active Cell

And you can also select a range starting from the active cell.

Range(ActiveCell.Offset(1, 1), ActiveCell.Offset(5, 5)).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
    • SELECT ALL the Cells in a Worksheet using a VBA Code
    • 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

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

    Свойство ActiveCell объекта Application возвращает объект Range, представляющий активную ячейку на активном листе в активном или указанном окне приложения Excel. Если окно не отображает лист, применение свойства Application.ActiveCell приведет к ошибке.

    Если свойство ActiveCell применяется к активному окну приложения Excel, то идентификатор объекта (Application или ActiveWindow) можно в коде VBA Excel не указывать. Следующие выражения, скопированные с сайта разработчиков, являются эквивалентными:

    ActiveCell

    Application.ActiveCell

    ActiveWindow.ActiveCell

    Application.ActiveWindow.ActiveCell

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

    Sub Primer1()

        With Windows(«Книга2.xlsx»)

            .ActiveCell = 325

            MsgBox .ActiveCell.Address

            MsgBox .ActiveCell.Value

        End With

    End Sub

    Программно сделать ячейку активной в VBA Excel можно с помощью методов Activate и Select.

    Различие методов Activate и Select

    Выберем программно диапазон «B2:E6» методом Select и выведем адрес активной ячейки:

    Sub Primer2()

        Range(«B2:E6»).Select

        ActiveCell = ActiveCell.Address

    End Sub

    Результат:

    Как видим, активной стала первая ячейка выбранного диапазона, расположенная слева вверху. Если мы поменяем местами границы диапазона (Range("E6:B2").Select), все равно активной станет та же первая ячейка.

    Теперь сделаем активной ячейку «D4», расположенную внутри выделенного диапазона, с помощью метода Activate:

    Sub Primer3()

        Range(«E6:B2»).Select

        Range(«D4»).Activate

        ActiveCell = ActiveCell.Address

    End Sub

    Результат:

    Как видим, выбранный диапазон не изменился, а активная ячейка переместилась из первой ячейки выделенного диапазона в ячейку «D4».

    И, наконец, выберем ячейку «D4», расположенную внутри выделенного диапазона, с помощью метода Select:

    Sub Primer4()

        Range(«E6:B2»).Select

        Range(«D4»).Select

        ActiveCell = ActiveCell.Address

    End Sub

    Результат:

    Как видим, ранее выбранный диапазон был заменен новым, состоящим из одной ячейки «D4». Такой же результат будет и при активации ячейки, расположенной вне выбранного диапазона, методом Activate:

    Sub Primer5()

        Range(«E6:B2»).Select

        Range(«A3»).Activate

        ActiveCell = ActiveCell.Address

    End Sub

    Аналогично ведут себя методы Activate и Select при работе с выделенной группой рабочих листов.

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


    Содержание

    1. Selecting and Activating Cells
    2. Using the Select Method and the Selection Property
    3. Selecting Cells on the Active Worksheet
    4. Activating a Cell Within a Selection
    5. Support and feedback
    6. CELL function
    7. Syntax
    8. info_type values
    9. CELL format codes
    10. Excel VBA Ranges and Cells
    11. Ranges and Cells in VBA
    12. Cell Address
    13. A1 Notation
    14. R1C1 Notation
    15. Range of Cells
    16. A1 Notation
    17. R1C1 Notation
    18. Writing to Cells
    19. Reading from Cells
    20. Non Contiguous Cells
    21. VBA Coding Made Easy
    22. Intersection of Cells
    23. Offset from a Cell or Range
    24. Offset Syntax
    25. Offset from a cell
    26. Offset from a Range
    27. Setting Reference to a Range
    28. Resize a Range
    29. Resize Syntax
    30. OFFSET vs Resize
    31. All Cells in Sheet
    32. UsedRange
    33. CurrentRegion
    34. Range Properties
    35. Last Cell in Sheet
    36. Last Used Row Number in a Column
    37. Last Used Column Number in a Row
    38. Cell Properties
    39. Common Properties
    40. Cell Font
    41. Copy and Paste
    42. Paste All
    43. Paste Special
    44. AutoFit Contents
    45. More Range Examples
    46. For Each
    47. Range Address
    48. Range to Array
    49. Array to Range
    50. Sum Range
    51. Count Range
    52. VBA Code Examples Add-in

    Selecting and Activating Cells

    In Microsoft Excel, you usually select a cell or cells and then perform an action, such as formatting the cells or entering values in them. In Visual Basic, it is usually not necessary to select cells before modifying them.

    For example, to enter a formula in cell D6 using Visual Basic, you don’t need to select the range D6. Just return the Range object for that cell, and then set the Formula property to the formula you want, as shown in the following example.

    For more information and examples of using other methods to control cells without selecting them, see How to: Reference Cells and Ranges.

    Using the Select Method and the Selection Property

    The Select method activates sheets and objects on sheets; the Selection property returns an object that represents the current selection on the active sheet in the active workbook. Before you can use the Selection property successfully, you must activate a workbook, activate or select a sheet, and then select a range (or other object) using the Select method.

    The macro recorder will often create a macro that uses the Select method and the Selection property. The following Sub procedure was created using the macro recorder, and it shows how Select and Selection work together.

    The following example performs the same task without activating or selecting the worksheet or cells.

    Selecting Cells on the Active Worksheet

    If you use the Select method to select cells, be aware that Select works only on the active worksheet. If you run your Sub procedure from the module, the Select method will fail unless your procedure activates the worksheet before using the Select method on a range of cells. For example, the following procedure copies a row from Sheet1 to Sheet2 in the active workbook.

    Activating a Cell Within a Selection

    Use the Activate method to activate a cell within a selection. There can be only one active cell, even when a range of cells is selected. The following procedure selects a range and then activates a cell within the range without changing the selection.

    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.

    Источник

    CELL function

    The CELL function returns information about the formatting, location, or contents of a cell. For example, if you want to verify that a cell contains a numeric value instead of text before you perform a calculation on it, you can use the following formula:

    This formula calculates A1*2 only if cell A1 contains a numeric value, and returns 0 if A1 contains text or is blank.

    Note: Formulas that use CELL have language-specific argument values and will return errors if calculated using a different language version of Excel. For example, if you create a formula containing CELL while using the Czech version of Excel, that formula will return an error if the workbook is opened using the French version. If it is important for others to open your workbook using different language versions of Excel, consider either using alternative functions or allowing others to save local copies in which they revise the CELL arguments to match their language.

    Syntax

    The CELL function syntax has the following arguments:

    A text value that specifies what type of cell information you want to return. The following list shows the possible values of the Info_type argument and the corresponding results.

    The cell that you want information about.

    If omitted, the information specified in the info_type argument is returned for cell selected at the time of calculation. If the reference argument is a range of cells, the CELL function returns the information for active cell in the selected range.

    Important: Although technically reference is optional, including it in your formula is encouraged, unless you understand the effect its absence has on your formula result and want that effect in place. Omitting the reference argument does not reliably produce information about a specific cell, for the following reasons:

    In automatic calculation mode, when a cell is modified by a user the calculation may be triggered before or after the selection has progressed, depending on the platform you’re using for Excel. For example, Excel for Windows currently triggers calculation before selection changes, but Excel for the web triggers it afterward.

    When Co-Authoring with another user who makes an edit, this function will report your active cell rather than the editor’s.

    Any recalculation, for instance pressing F9, will cause the function to return a new result even though no cell edit has occurred.

    info_type values

    The following list describes the text values that can be used for the info_type argument. These values must be entered in the CELL function with quotes (» «).

    Reference of the first cell in reference, as text.

    Column number of the cell in reference.

    The value 1 if the cell is formatted in color for negative values; otherwise returns 0 (zero).

    Note: This value is not supported in Excel for the web, Excel Mobile, and Excel Starter.

    Value of the upper-left cell in reference; not a formula.

    Filename (including full path) of the file that contains reference, as text. Returns empty text («») if the worksheet that contains reference has not yet been saved.

    Note: This value is not supported in Excel for the web, Excel Mobile, and Excel Starter.

    Text value corresponding to the number format of the cell. The text values for the various formats are shown in the following table. Returns «-» at the end of the text value if the cell is formatted in color for negative values. Returns «()» at the end of the text value if the cell is formatted with parentheses for positive or all values.

    Note: This value is not supported in Excel for the web, Excel Mobile, and Excel Starter.

    The value 1 if the cell is formatted with parentheses for positive or all values; otherwise returns 0.

    Note: This value is not supported in Excel for the web, Excel Mobile, and Excel Starter.

    Text value corresponding to the «label prefix» of the cell. Returns single quotation mark (‘) if the cell contains left-aligned text, double quotation mark («) if the cell contains right-aligned text, caret (^) if the cell contains centered text, backslash () if the cell contains fill-aligned text, and empty text («») if the cell contains anything else.

    Note: This value is not supported in Excel for the web, Excel Mobile, and Excel Starter.

    The value 0 if the cell is not locked; otherwise returns 1 if the cell is locked.

    Note: This value is not supported in Excel for the web, Excel Mobile, and Excel Starter.

    Row number of the cell in reference.

    Text value corresponding to the type of data in the cell. Returns «b» for blank if the cell is empty, «l» for label if the cell contains a text constant, and «v» for value if the cell contains anything else.

    Returns an array with 2 items.

    The 1st item in the array is the column width of the cell, rounded off to an integer. Each unit of column width is equal to the width of one character in the default font size.

    The 2nd item in the array is a Boolean value, the value is TRUE if the column width is the default or FALSE if the width has been explicitly set by the user.

    Note: This value is not supported in Excel for the web, Excel Mobile, and Excel Starter.

    CELL format codes

    The following list describes the text values that the CELL function returns when the Info_type argument is «format» and the reference argument is a cell that is formatted with a built-in number format.

    Источник

    Excel VBA Ranges and Cells

    In this Article

    Ranges and Cells in VBA

    Excel spreadsheets store data in Cells. Cells are arranged into Rows and Columns. Each cell can be identified by the intersection point of it’s row and column (Exs. B3 or R3C2).

    An Excel Range refers to one or more cells (ex. A3:B4)

    Cell Address

    A1 Notation

    In A1 notation, a cell is referred to by it’s column letter (from A to XFD) followed by it’s row number(from 1 to 1,048,576). This is called a cell address.

    In VBA you can refer to any cell using the Range Object.

    R1C1 Notation

    In R1C1 Notation a cell is referred by R followed by Row Number then letter ‘C’ followed by the Column Number. eg B4 in R1C1 notation will be referred by R4C2. In VBA you use the Cells Object to use R1C1 notation:

    Range of Cells

    A1 Notation

    To refer to a more than one cell use a “:” between the starting cell address and last cell address. The following will refer to all the cells from A1 to D10:

    R1C1 Notation

    To refer to a more than one cell use a “,” between the starting cell address and last cell address. The following will refer to all the cells from A1 to D10:

    Writing to Cells

    To write values to a cell or contiguous group of cells, simple refer to the range, put an = sign and then write the value to be stored:

    Reading from Cells

    To read values from cells, simple refer to the variable to store the values, put an = sign and then refer to the range to be read:

    Note: To store values from a range of cells, you need to use an Array instead of a simple variable.

    Non Contiguous Cells

    To refer to non contiguous cells use a comma between the cell addresses:

    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!

    Intersection of Cells

    To refer to non contiguous cells use a space between the cell addresses:

    Offset from a Cell or Range

    Using the Offset function, you can move the reference from a given Range (cell or group of cells) by the specified number_of_rows, and number_of_columns.

    Offset Syntax

    Offset from a cell

    Offset from a Range

    Setting Reference to a Range

    To assign a range to a range variable: declare a variable of type Range then use the Set command to set it to a range. Please note that you must use the SET command as RANGE is an object:

    Resize a Range

    Resize method of Range object changes the dimension of the reference range:

    Top-left cell of the Resized range is same as the top-left cell of the original range

    Resize Syntax

    OFFSET vs Resize

    Offset does not change the dimensions of the range but moves it by the specified number of rows and columns. Resize does not change the position of the original range but changes the dimensions to the specified number of rows and columns.

    All Cells in Sheet

    The Cells object refers to all the cells in the sheet (1048576 rows and 16384 columns).

    UsedRange

    UsedRange property gives you the rectangular range from the top-left cell used cell to the right-bottom used cell of the active sheet.

    CurrentRegion

    CurrentRegion property gives you the contiguous rectangular range from the top-left cell to the right-bottom used cell containing the referenced cell/range.

    Range Properties

    You can get Address, row/column number of a cell, and number of rows/columns in a range as given below:

    Last Cell in Sheet

    You can use Rows.Count and Columns.Count properties with Cells object to get the last cell on the sheet:

    Last Used Row Number in a Column

    END property takes you the last cell in the range, and End(xlUp) takes you up to the first used cell from that cell.

    Last Used Column Number in a Row

    END property takes you the last cell in the range, and End(xlToLeft) takes you left to the first used cell from that cell.

    You can also use xlDown and xlToRight properties to navigate to the first bottom or right used cells of the current cell.

    Cell Properties

    Common Properties

    Here is code to display commonly used Cell Properties

    Cell Font

    Cell.Font object contains properties of the Cell Font:

    Copy and Paste

    Paste All

    Ranges/Cells can be copied and pasted from one location to another. The following code copies all the properties of source range to destination range (equivalent to CTRL-C and CTRL-V)

    Paste Special

    Selected properties of the source range can be copied to the destination by using PASTESPECIAL option:

    Here are the possible options for the Paste option:

    AutoFit Contents

    Size of rows and columns can be changed to fit the contents using AutoFit:

    More Range Examples

    It is recommended that you use Macro Recorder while performing the required action through the GUI. It will help you understand the various options available and how to use them.

    For Each

    It is easy to loop through a range using For Each construct as show below:

    At each iteration of the loop one cell in the range is assigned to the variable cell and statements in the For loop are executed for that cell. Loop exits when all the cells are processed.

    Sort is a method of Range object. You can sort a range by specifying options for sorting to Range.Sort. The code below will sort the columns A:C based on key in cell C2. Sort Order can be xlAscending or xlDescending. Header:= xlYes should be used if first row is the header row.

    Find is also a method of Range Object. It find the first cell having content matching the search criteria and returns the cell as a Range object. It return Nothing if there is no match.

    Use FindNext method (or FindPrevious) to find next(previous) occurrence.

    Following code will change the font to “Arial Black” for all cells in the range which start with “John”:

    Following code will replace all occurrences of “To Test” to “Passed” in the range specified:

    It is important to note that you must specify a range to use FindNext. Also you must provide a stopping condition otherwise the loop will execute forever. Normally address of the first cell which is found is stored in a variable and loop is stopped when you reach that cell again. You must also check for the case when nothing is found to stop the loop.

    Range Address

    Use Range.Address to get the address in A1 Style

    Use xlReferenceStyle (default is xlA1) to get addres in R1C1 style

    This is useful when you deal with ranges stored in variables and want to process for certain addresses only.

    Range to Array

    It is faster and easier to transfer a range to an array and then process the values. You should declare the array as Variant to avoid calculating the size required to populate the range in the array. Array’s dimensions are set to match number of values in the range.

    Array to Range

    After processing you can write the Array back to a Range. To write the Array in the example above to a Range you must specify a Range whose size matches the number of elements in the Array.

    Use the code below to write the Array to the range D1:D5:

    Please note that you must Transpose the Array if you write it to a row.

    Sum Range

    You can use many functions available in Excel in your VBA code by specifying Application.WorkSheetFunction. before the Function Name as in the example above.

    Count Range

    Written by: Vinamra Chandra

    VBA Code Examples Add-in

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

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

    Источник

    Всё о работе с ячейками в 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
    

    ‘Active Cell’ is an important concept in Excel.

    While you don’t have to care about the active cell when you’re working on the worksheet, it’s an important thing to know when working with VBA in Excel.

    Proper use of the active cell in Excel VBA can help you write better code.

    In this tutorial, I first explained what is an active cell, and then show you some examples of how to use an active cell in VBA in Excel.

    What is an Active Cell in Excel?

    An active cell, as the name suggests, is the currently active cell that will be used when you enter any text or formula in Excel.

    For example, if I select cell B5, then B5 becomes my active cell in the worksheet. Now if I type anything from my keyboard, it would be entered in this cell, because this is the active cell.

    While this may sound obvious, here is something not that obvious – when you select a range of cells, even then you would only have one active cell.

    For example, if I select A1:B10, although I have 20 selected cells, I still have only one single active cell.

    So now, if I start typing any text or formula, it would only be entered in the active cell.

    You can identify the active cell by looking at the difference in color between the active cell in all the other cells in the selection. You would notice that the active cell is of a lighter shade than the other selected cells.

    Active cell is highlighted in a different color

    Another quick way to know which cell is the active cell is by looking at the Name box (the field that is next to the formula bar). The cell reference of the active cell would be shown in the Name Box.

    Active cell address is shown in the name box

    Using Active Cell in VBA in Excel

    Now that I’ve explained what is an active cell in a worksheet in excel, let’s learn how an Active cell can be used in Excel VBA.

    Active Cell Properties and Methods

    In VBA, you can use an active cell in two ways:

    1. To get the information about it (these are called Properties)
    2. To perform some action on it (these are called Methods)

    Here is how you can access all the properties and methods of an active cell in VBA:

    1. Open a Module in Excel VBA editor
    2. Type the phrase ‘ActiveCell’
    3. Enter a dot (.) after the word ActiveCell

    As soon as you do this, you would notice that a set of properties and methods appear as a drop-down (this is called an IntelliSense in Excel VBA).

    In the drop-down that appears, you would see two types of options – the one that has a green icon and the one that has a gray icon (with a hand).

    The one with the grey icons is the Properties, and the one with the green icons is the Methods.

    Some examples of Methods would include Activate, AddComment, Cut, Delete, Clear, etc. As you can notice, these are actions that can be performed on the active cell.

    Some examples of Properties would include Address, Font, HasFormula, Interior.Color. All these are properties of the active cell that gives you information about that active cell.

    For example, you can use this to get the cell address of the active cell or change the interior cell color of the cell.

    Now let’s have a few simple VBA code examples that you can use in your day-to-day work when working with active cell in excel

    Making a Cell the Active Cell

    To make any cell the active cell, you first have to make sure that it is selected.

    If you only have one single cell selected, it by default becomes the active cell.

    Below is the VBA code to make cell B5 the active cell:

    Sub Change_ActiveCell()
    Range("B5").Activate
    End Sub

    In the above VBA code, I have first specified the cell address of the cell that I want to activate (which is B5), and then I use the activate method to make it the active cell.

    When you only want to make one single cell the active cell, you can also use the select method (code below):

    Sub Change_ActiveCell()
    Range("B5").Select
    End Sub

    As I mentioned earlier, you can only have one active cell even if you have a range of cell selected.

    With VBA, you can first select a range of cells, and then make any one of those cells the active cell.

    Below the VBA code that would first select range A1:B10, and then make cell A5 the active cell:

    Sub Select_ActiveCell()
    Range("A1:B10").Select
    Range("A5").Activate
    End Sub

    Clear the Active Cell

    Below is the VBA code that would first make cell A5 the active cell, and then clear its content (cell content as well any formatting applied to the cell).

    Sub Clear_ActiveCell()
    Range("A5").Activate
    ActiveCell.Clear
    End Sub

    Note that I have shown you the above code just to show you how the clear method work with active cell. In VBA, you don’t need to always select or activate the cell to perform any method on it.

    For example, you can also clear the content of cell A5 using the below code:

    Sub Clear_CellB5()
    Range("A5").Clear
    End Sub

    Get the Value from the Active Cell

    Below the VBA code that could show you a message box displaying the value in the active cell:

    Sub Show_ActiveCell_Value()
    MsgBox ActiveCell.Value
    End Sub

    Similarly, you can also use a simple VBA code to show the cell address of the active cell (code below):

    Sub Show_ActiveCell_Address()
    MsgBox ActiveCell.Address
    End Sub

    The above code would show the address in absolute reference (such as $A$5).

    Showing the cell address of the active cell

    Formating the Active Cell (Color, Border)

    Below the VBA code that would make the active cell blue in color and change the font color to white.

    Sub Format_ActiveCell()
    
    'Makes the active cell blue in color
    ActiveCell.Interior.Color = vbBlue
    
    'Changes the cell font color to white
    ActiveCell.Font.Color = vbWhite
    
    End Sub

    Note that I have used the inbuilt color constant (vbBlue and vbWhite). You can also use the RGB constant. For example, instead of vbRed, you can use RGB(255, 0, 0)

    Offsetting From the Active Cell

    VBA in Excel allows you to refer to cells relative to the position of the active cell (this is called offsetting).

    For example, if my active cell is cell A1, I can use the offset property on the active cell and refer to the cell below it by specifying the position of that row corresponding to the active cell.

    Let me show you an example.

    Sub Offset_From_ActiveCell()
    
    'Make cell A1 the Active Cell
    Range("A1").Activate
    
    'Goes One cell Below the Actice Cell and Enters the text Test in it
    ActiveCell.Offset(1, 0).Value = "Test"
    
    End Sub

    The above code first activate cell A1 and makes it the active cell. It then uses the offset property on the active cell, to refer to the cell which is one row below it.

    And in the same line in the code, I have also assigned a value “Test” to that cell which is one row below the active cell.

    Let me show you another example where offsetting from the active cell could be used in a practical scenario.

    Below I have a VBA code that first activates cell A1, and then uses the offset property to cover 10 cells below the active cell and enter numbers from 1 to 10 in cell A1:A10.

    Sub Offset_From_ActiveCell()
    
    'Activates cell A1
    Range("A1").Activate
    
    'Loop to go through 10 cells below the active cell and enter sequential numbers in it
    For i = 1 To 10
        ActiveCell.Offset(i - 1, 0).Value = i
    Next i
    
    End Sub
    

    The above code uses a For Next loop that runs 10 times (and each time the value of the variable ‘i’ increases by 1). And since I am also using ‘i’ in the offset property, it keeps going one cell down with each iteration.

    Get ActiveCell Row or Column Number

    Below the VBA code that will show you the row number of the active cell in message box:

    Sub ActiveCell_RowNumber()
    MsgBox ActiveCell.Row
    End Sub

    And the below code will show you the column number in a message box:

    Sub ActiveCell_ColumnNumber()
    MsgBox ActiveCell.Column
    End Sub

    Assign Active Cell Value to a Variable

    You can also use VBA to assign the active cell to a variable. Once this is done, you can use this variable instead of the active cell in your code.

    And how does this help? Good Question!

    When you assign the active cell to a variable, you can continue to use this variable instead of the active cell. The benefit here is that unlike the active cell (which can change when other sheets or workbooks are activated) your variable would continue to refer to the original active cell it was assigned to.

    So if you are writing a VBA code that cycles through each worksheet and activates these worksheets, while your active cell would change as new sheets are activated, the variable to which you assigned the active cell initially wouldn’t change.

    Below is an example code that defines a variable ‘varcell’ and assigns the active cell to this variable.

    Sub Assign_ActiveCell()
    Dim varcell As Range
    Set varcell = ActiveCell
    MsgBox varcell.Value
    End Sub

    Select a Range of Cells Starting from the Active Cell

    And the final thing I want to show you about using active cell in Excel VBA is to select an entire range of cells starting from the active cell.

    A practical use case of this could be when you want to quickly format a set of cells in every sheet in your workbook.

    Below is the VBA code that would select cells in 10 rows and 10 columns starting from the active cell:

    Sub Select_from_Activecell()
    Range(ActiveCell, ActiveCell.Offset(10, 10)).Select
    End Sub

    When we specify two cell references inside the Range property, VBA refers to the entire range covered between there two references.

    For example, Range(Range(“A1”), Range(“A10”)).Select would select cell A1:A10.

    Similarly, I have used it with active cell, Where the first reference is the active cell itself, and the second reference offsets the active cell by 10 rows and 10 columns.

    I hope this tutorial has been useful for you in understanding how active cell works in Excel VBA.

    Other Excel tutorials you may also find useful:

    • Highlight the Active Row and Column in a Data Range in Excel
    • 24 Useful Excel Macro Examples for VBA Beginners (Ready-to-use)
    • How to Filter Cells with Bold Font Formatting in Excel (An Easy Guide)
    • How to Delete Entire Row in Excel Using VBA
    • Copy and Paste Multiple Cells in Excel (Adjacent & Non-Adjacent)
    • Working with Worksheets using Excel VBA (Explained with Examples)
    • Using Workbook Object in Excel VBA (Open, Close, Save, Set)
    • Excel VBA Events – An Easy (and Complete) Guide
    • How to Edit Cells in Excel? (Shortcuts)

    Понравилась статья? Поделить с друзьями:
  • Action words word search
  • Action word что это
  • Action word with pictures
  • Action word for talking
  • Action word for talk