Vba excel activecell что это

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


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

    Active Cell in Excel VBA

    The active cell is the currently selected cell in a worksheet. The active cell in VBA can be used as a reference to move to another cell or change the properties of the same active cell or the cell reference provided by the active cell. We can access an active cell in VBA by using the application.property method with the keyword active cell.

    Understanding the concept of range object and cell properties in VBACells are cells of the worksheet, and in VBA, when we refer to cells as a range property, we refer to the same cells. In VBA concepts, cells are also the same, no different from normal excel cells.read more is important to work efficiently with VBA codingVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more. One more concept you need to look into in these concepts is “VBA Active Cell.”

    In Excel, there are millions of cells, and you are unsure which one is an active cell. For example, look at the below image.

    Active cell address

    In the above pic, we have many cells. Finding which one is an active cell is very simple; whichever cell is selected. It is called an “active cell” in VBA.

    Look at the name boxIn Excel, the name box is located on the left side of the window and is used to give a name to a table or a cell. The name is usually the row character followed by the column number, such as cell A1.read more if your active cell is not visible in your window. It will show you the active cell address. For example, in the above image, the active cell address is B3.

    Even when many cells are selected as a range of cells, whatever the first cell is in, the selection becomes the active cell. For example, look at the below image.

    Active cell address range

    Table of contents
    • Active Cell in Excel VBA
      • #1 – Referencing in Excel VBA
      • #2 – Active Cell Address, Value, Row, and Column Number
      • #3 – Parameters of Active Cell in Excel VBA
      • Recommended Articles

    #1 – Referencing in Excel VBA

    In our earlier articles, we have seen how to reference the cellsCell reference in excel is referring the other cells to a cell to use its values or properties. For instance, if we have data in cell A2 and want to use that in cell A1, use =A2 in cell A1, and this will copy the A2 value in A1.read more in VBA. By active cell property, we can refer to the cell.

    For example, if we want to select cell A1 and insert the value “Hello,” we can write it in two ways. Below is the way of selecting the cell and inserting the value using the VBA “RANGE” object

    Code:

    Sub ActiveCell_Example1()
    
        Range("A1").Select
        Range("A1").Value = "Hello"
     
    End Sub

    VBA Active Cell Example 1

    It will first select the cell A1 “Range(“A1″). Select”

    Then, it will insert the value “Hello” in cell A1 Range(“A1”).Value = “Hello”

    Now, we will remove the line Range(“A1”). Value = “Hello” and use the active cell property to insert the value.

    Code:

    Sub ActiveCell_Example1()
    
        Range("A1").Select
        ActiveCell.Value = "Hello"
    
    End Sub

    VBA Active Cell Example 1-1

    Similarly, first, it will select the cell A1 “Range(“A1”). Select.

    But here, we have used ActiveCell.Value = “Hello” instead of Range(“A1”).Value = “Hello”

    We have used the active cell property because the moment we select cell A1 it becomes an active cell. So, we can use the Excel VBA active cell property to insert the value.

    #2 – Active Cell Address, Value, Row, and Column Number

    Let’s show the active cell’s address in the message box to understand it better. Now, look at the below image.

    VBA Active Cell Example 2

    In the above image, the active cell is “B3,” and the value is 55. So, let us write code in VBA to get the active cell’s address.

    Code:

    Sub ActiveCell_Example2()
    
        MsgBox ActiveCell.Address
    
    End Sub

    VBA Active Cell Example 2-1

    Run this code using the F5 key or manually. Then, it will show the active cell’s address in a message box.

    VBA Active Cell Example 2-2

    Output:

    VBA Active Cell Example 2-3

    Similarly, the below code will show the value of the active cell.

    Code:

    Sub ActiveCell_Example2()
    
        MsgBox ActiveCell.Value
    
    End Sub

    VBA Active Cell Example 2-4

    Output:

    VBA Active Cell Example 2-5

    The below code will show the row number of the active cell.

    Code:

    Sub ActiveCell_Example2()
    
      MsgBox ActiveCell.Row
    
    End Sub

    VBA Active Cell Example 2-6

    Output:

    Example 2-7

    The below code will show the column number of the active cell.

    Code:

    Sub ActiveCell_Example2()
    
    MsgBox ActiveCell.Column
    
    End Sub

    Example 2-8

    Output:

    VBA Active Cell Example 2-9

    #3 – Parameters of Active Cell in Excel VBA

    The active cell property has parameters as well. After entering the property, the active cell opens parenthesis to see the parameters.

    VBA Active Cell Formula

    Using this parameter, we can refer to another cell as well.

    For example, ActiveCell (1,1) means whichever cell is active. If you want to move down one row to the bottom, you can use ActiveCell (2,1). Here 2 does not mean moving down two rows but rather just one row down. Similarly, if you want to move one column to the right, then this is the code ActiveCell (2,2)

    Look at the below image.

    VBA Active Cell Example 3

    In the above image, the active cell is A2. To insert value to the active cell, you write this code.

    Code:

    ActiveCell.Value = “Hiiii” or ActiveCell (1,1).Value = “Hiiii”

    VBA Active Cell Example 3-4

    Run this code manually or through the F5 key. It will insert the value “Hiiii” into the cell.

    Example 3-7

    If you want to insert the same value to the below cell, you can use this code.

    Code:

    ActiveCell (2,1).Value = “Hiiii”

    Example 3-5

    It will insert the value to the cell below the active cell.

    Example 3-2

    You can use this code if you want to insert the value to one column right then.

    Code:

    ActiveCell (1,2).Value = “Hiiii”

    Example 3-6

    It will insert “Hiiii” to the next column cell of the active cell.

    Example 3-3

    Like this, we can reference the cells in VBA using the active cell property.

    We hope you have enjoyed it. Thanks for your time with us.

    You can download the VBA Active Cell Excel Template here:- VBA Active Cell Template

    Recommended Articles

    This article has been a guide to VBA Active Cell. Here, we learned the concept of an active cell to find the address of a cell. Also, we learned the parameters of the active cell in Excel VBA along with practical examples and a downloadable template. Below you can find some useful Excel VBA articles: –

    • VBA Selection
    • Excel Edit Cell Shortcut
    • Excel VBA Range Cells
    • Get Cell Value with Excel VBA

    ‘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)

    Return to VBA Code Examples

    This tutorial will demonstrate how to set (and work with) the ActiveCell using VBA.

    The ActiveCell property in VBA returns the address of the cell that is selected (active) in your worksheet. We can move the cell pointer to a specific cell using VBA by setting the ActiveCell property to a specific cell, and we can also read the values of the currently active cell with VBA.

    Set ActiveCell

    Setting the active cell in VBA is very simple – you just refer to a range as the active cell.

    Sub Macro1()
       ActiveCell = Range("F2")
    End Sub

    This will move your cell pointer to cell F2.

    Get Value of ActiveCell

    We can get the value of an active cell by populating a variable.

    For example, if the value in F2 if 300, we can return this value to a declared variable.

    Sub TestMacro()
     Dim dblValue As Double
     dblValue = ActiveCell
     MsgBox dblValue
    End Sub

    when we run the code, the variable dblValue will be populated with the value in the ActiveCell.

    vba active cell

    If we then allow the code to continue, a message box will pop up with the value.

    vba activecell msgbox

    Get ActiveCell in Worksheet_Change Event

    When you change any data in your worksheet, the Worksheet_Change Event is fired.

    vba activecell change event

    The Change event contains one argument  –  (ByVal Target as Range). The Range referred to in this variable Target is either a range of cells or a single cell that is currently selected in your worksheet. If you have only one cell selected in the worksheet, then the Target variable is equal to the ActiveCell.

    Private Sub Worksheet_Change(ByVal Target As Range)
      If Target = Range("F2") Then
        MsgBox "The Active cell is F2!"
      End If
    End Sub

    Note that this event only fires when you amend the data in your worksheet – so when you add or change data, it does not fire by moving your cell pointer around the worksheet.

    VBA Active Cell

    VBA Active Cell

    Active cell means the specific cell which is active in the current active worksheet. For example, if in sheet 2 cell B4 is selected means the active cell is B4 in sheet 2. In VBA we use a reference of active cell to change the properties or values of the active cell. OR we use this function in certain situations when we need to make some changes in the active cell on some certain conditions which meet the requirements.

    The active cell is a property in VBA. We use it in different situations in VBA. We can assign values to an active cell using VBA Active Cell function or fetch the address of the active cell. What did these functions return? Active cell Function returns the range property of the active cell in the active worksheet. As explained in the above statement in the definition if sheet 2 is active and cell B4 is active cell the active cell function in VBA will fetch the range properties of the cell B4 in sheet 2.

    Syntax of Active Cell in Excel VBA

    Below is the syntax of Active Cell in Excel VBA

    Syntax of ActiveCell

    The syntax is used to assign a certain value to the active cell.

    Activecell.Value= “ “

    The syntax will select the value or the property of the active cell in the active worksheet.

    Application.Activecell

    If we need to change the font of the active cell then the syntax will be as follows

    Activecell.Font.(The font we want) = True

    We can also display the rows and column of the active cell using the following syntax

    Application.Activecell

    Let us use the above syntax explained in a few examples and learn how to play with the active cells.

    Note: In order to use VBA make sure to have developer’s tab enabled from File Tab from the options section.

    Examples of Excel VBA Active Cell

    Below are the different examples of VBA Active Cell in Excel:

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

    VBA Active Cell – Example #1

    In this example, we want to change the value of the current cell with something cell. For example in sheet 1, select cell A2 and insert value as ANAND and we want to change the value for that active cell as ARAN.

    Follow the below steps to use VBA Active Cell in Excel.

    Step 1: Go to Developer’s tab and click on Visual Basic to open VB Editor.

    VBA Active Cell Example 1-1

    Step 2: Click on Insert tab and click on modules to insert a new module.

    VBA Active Cell Example 1-2

    Step 3: Declare a sub-function to start writing the code.

    Code:

    Sub Sample()
    
    End Sub

    VBA Active Cell Example 1-3

    Step 4: Activate the worksheet 1 by using the below function.

    Code:

    Sub Sample()
    
    Worksheets("Sheet1").Activate
    
    End Sub

    VBA Active Cell Example 1-4

    Step 5: We can check that in cell A2 in sheet 1 we have the value as ANAND and it is the active cell.

    VBA Active Cell Example 1-5

    Step 6: Now use the following statement to change the value of the active cell.

    Code:

    Sub Sample()
    
    Worksheets("Sheet1").Activate
    
    ActiveCell.Value = "ARAN"
    
    End Sub

    VBA Active Cell Example 1-6

    Step 7: Run the above code from the run button provided or press F5.

    Result of Example 1-7

    We can see that the value in cell A2 has been changed.

    VBA Active Cell – Example #2

    Now we have changed the active cell Value from ANAND to ARAN. How do we display the current value of the active cell? This we will learn in this example.

    Follow the below steps to use VBA Active Cell in Excel.

    Step 1: Go to the developer’s Tab and click on Visual Basic to Open VB Editor.

    Step 2: In the same module declare a sub-function to start writing the code.

    Code:

    Sub Sample1()
    
    End Sub

    VBA Active Cell Example 2-1

    Step 3: Activate the worksheet 1 by the following code.

    Code:

    Sub Sample1()
    
    Worksheets("Sheet1").Activate
    
    End Sub

    VBA Active Cell Example 2-2

    Step 4: Now let us select the active cell by the following code.

    Code:

    Sub Sample1()
    
    Worksheets("Sheet1").Activate
    Set selectedCell = Application.ActiveCell
    
    End Sub

    VBA Active Cell Example 2-3

    Step 5: Now let us display the value of the selected cell by the following code.

    Code:

    Sub Sample1()
    
    Worksheets("Sheet1").Activate
    Set selectedCell = Application.ActiveCell
    MsgBox selectedCell.Value
    
    End Sub

    VBA Active Cell Example 2-4

    Step 6: Run the above code by pressing F5 or by the run button provided and see the following result.

    Result of Example 2-5

    The active cell was A2 and it has the value as ARAN so the displayed property is ARAN.

    VBA Active Cell – Example #3

    Let us change the font of the cell A2 which was the selected cell. Let us make the font as BOLD. Initially, there was no font selected.

    For this, Follow the below steps to use VBA Active Cell in Excel.

    Step 1: Go to the Developer’s Tab and click on Visual Basic to open VB Editor.

    Step 2: In the same module declare a sub-function to start writing the code.

    Code:

    Sub Sample2()
    
    End Sub

    VBA Active Cell Example 3-1

    Step 3: Let us activate the worksheet first in order to use the active cell.

    Code:

    Sub Sample2()
    
    Worksheets("Sheet1").Activate
    
    End Sub

    VBA Active Cell Example 3-2

    Step 4: Let us change the font of the selected cell by the following code.

    Code:

    Sub Sample2()
    
    Worksheets("Sheet1").Activate
    
    ActiveCell.Font.Bold = True
    
    End Sub

    VBA Active Cell Example 3-3

    Step 5: Run the above code by pressing F5 or by the run button provided and see the result.

    Result of Example 3-4

    The font of the active cell is changed to BOLD.

    VBA Active Cell – Example #4

    Now we want to know what row or what column the currently active cell is in. How to do this is what we will learn in this example.

    For this, Follow the below steps to use VBA Active Cell in Excel.

    Step 1: Go to Developer’s Tab and click on Visual Basic to Open the VB Editor.

    Step 2: In the same module declare a sub-function to start writing the code.

    Code:

    Sub Sample3()
    
    End Sub

    VBA Active Cell Example 4-1

    Step 3: Let us activate the worksheet first in order to use the active cell properties.

    Code:

    Sub Sample3()
    
    Worksheets("Sheet1").Activate
    
    End Sub

    VBA Active Cell Example 4-2

    Step 4: Now we select the active cell by the following code.

    Code:

    Sub Sample3()
    
    Worksheets("Sheet1").Activate
    Set selectedCell = Application.ActiveCell
    
    End Sub

    VBA Active Cell Example 4-3

    Step 5: Now we can display the current row of the active cell by the following code.

    Code:

    Sub Sample3()
    
    Worksheets("Sheet1").Activate
    Set selectedCell = Application.ActiveCell
    MsgBox selectedCell.Row
    
    End Sub

    Example 4-4

    Step 6: We can also get the current column of the active cell by the following code.

    Code:

    Sub Sample3()
    
    Worksheets("Sheet1").Activate
    Set selectedCell = Application.ActiveCell
    MsgBox selectedCell.Row
    MsgBox selectedCell.Column
    
    End Sub

    Example 4-5

    Step 7: Now press F5 or the run button provided to run the above code and see the following result.

    Result of Example 4-6

    The above result was the row of the active cell. Press ok to see the column of the active cell.

    Things to Remember

    There are few things which we need to remember about Active cell in VBA:

    • The active cell is the currently active or selected cell in any worksheet.
    • We can display or change the properties of the active cell address in VBA.
    • In order to use the properties of the active cell, we must need to activate the current worksheet first.

    Recommended Articles

    This has been a guide to Excel VBA Active Cell. Here we discussed how to use VBA Active Cell property to assign value or fetch the address of the active cell in Excel along with some practical examples and downloadable excel template. You can also go through our other suggested articles –

    1. VBA IFError
    2. VBA XML
    3. VBA Paste
    4. VBA RGB

    Содержание

    1. Working with the Active Cell
    2. Moving the Active Cell
    3. Selecting the Cells Surrounding the Active Cell
    4. Support and feedback
    5. Работа с активной ячейкой
    6. Перемещение активной ячейки
    7. Выделение ячеек вокруг активной ячейки
    8. Поддержка и обратная связь
    9. Выбор и активация ячеек
    10. Использование метода Select и свойства Selection
    11. Выбор ячеек на активном листе
    12. Активация ячейки в выделенном фрагменте
    13. Поддержка и обратная связь
    14. How to use ActiveCell in VBA in Excel
    15. Use the Active Cell Property
    16. Important Points
    17. Activate a Cell from the Selected Range
    18. Return Value from the Active Cell
    19. Set Active Cell to a Variable
    20. Get Row and Column Number of the ActiveCell
    21. Get Active Cell’s Address
    22. Move from the Active Cell using Offset
    23. Select a Range from the Active Cell
    24. VBA Excel. Свойство ActiveCell объекта Application
    25. Свойство Application.ActiveCell
    26. Различие методов Activate и Select

    Working with the Active Cell

    The ActiveCell property returns a Range object that represents the cell that is active. You can apply any of the properties or methods of a Range object to the active cell, as in the following example. While one or more worksheet cells may be selected, only one of the cells in the selection can be the ActiveCell.

    Note You can work with the active cell only when the worksheet that it is on is the active sheet.

    Moving the Active Cell

    Use the Range .Activate method to designate which cell is the active cell. For example, the following procedure makes B5 the active cell and then formats it as bold.

    Note To select a range of cells, use the Select method. To make a single cell the active cell, use the Activate method.

    Use the Offset property to move the active cell. The following procedure inserts text into the active cell in the selected range and then moves the active cell one cell to the right without changing the selection.

    Selecting the Cells Surrounding the Active Cell

    The CurrentRegion property returns a range or ‘island’ of cells bounded by blank rows and columns. In the following example, the selection is expanded to include the cells that contain data immediately adjoining the active cell. This range is then formatted with the Currency style.

    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.

    Источник

    Работа с активной ячейкой

    Свойство ActiveCell возвращает объект Range, представляющий активную ячейку. К активной ячейке можно применить любое свойство или метод объекта Range, как показано в следующем примере. Хотя можно выделить одну или несколько ячеек листа, в выделенном фрагменте только к одной ячейке можно применить свойство ActiveCell.

    Примечание Работать с активной ячейкой можно только в том случае, если лист, на который она находится, является активным листом.

    Перемещение активной ячейки

    Чтобы указать, какая ячейка является активной, используйте метод Range .Activate. Например, в следующей процедуре ячейка B5 назначается активной с последующим ее форматированием полужирным шрифтом.

    Примечание Чтобы выбрать диапазон ячеек, используйте метод Select . Чтобы сделать одну ячейку активной, используйте метод Activate.

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

    Выделение ячеек вокруг активной ячейки

    Свойство CurrentRegion возвращает диапазон или «остров» ячеек, ограниченный пустыми строками и столбцами. В следующем примере выделенный фрагмент расширяется для включения ячеек, содержащих данные, непосредственно примыкающие к активной ячейке. Затем этот диапазон форматируется с использованием денежного стиля.

    Поддержка и обратная связь

    Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

    Источник

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

    В Microsoft Excel обычно выбирается ячейка или ячейки, а затем выполняется действие, например форматирование ячеек или ввод значений. В Visual Basic обычно не требуется выбирать ячейки перед их изменением.

    Например, чтобы ввести формулу в ячейку D6 с помощью Visual Basic, не нужно выбирать диапазон D6. Просто возвратите объект Range для этой ячейки, а затем присвойте свойству Formula нужную формулу, как показано в следующем примере.

    Дополнительные сведения и примеры использования других методов для управления ячейками без их выбора см. в разделе Практическое руководство. Ссылка на ячейки и диапазоны.

    Использование метода Select и свойства Selection

    Метод Select активирует листы и объекты на листах; свойство Selection возвращает объект, представляющий текущее выделение на активном листе в активной книге. Перед использованием свойства Selection необходимо активировать книгу, активировать или выбрать лист, а затем выбрать диапазон (или другой объект) с помощью метода Select.

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

    В следующем примере выполняется та же задача без активации или выбора листа или ячеек.

    Выбор ячеек на активном листе

    Если для выбора ячеек используется метод Select, имейте в виду, что Select работает только на активном листе. Если выполнить процедуру Sub из модуля, метод Select завершится ошибкой, если процедура не активирует лист перед использованием метода Select для диапазона ячеек. Например, следующая процедура копирует строку из Листа1 в Лист2 в активной книге.

    Активация ячейки в выделенном фрагменте

    Используйте метод Activate для активации ячейки в выделенном фрагменте. Активной может быть только одна ячейка, даже если выделен диапазон ячеек. Следующая процедура выделяет диапазон и активирует ячейку в диапазоне, не изменяя выделенный фрагмент.

    Поддержка и обратная связь

    Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office 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’sactive 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.

    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.

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

    Set Active Cell to a Variable

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

    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.

    Get Active Cell’s Address

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

    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.

    Select a Range from the Active Cell

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

    Источник

    VBA Excel. Свойство ActiveCell объекта Application

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

    Свойство Application.ActiveCell

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

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

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

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

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

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

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

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

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

    Источник

    13.4. Свойства Application

    13.4.1. ActiveCell, ActiveChart, ActivePrinter, ActiveSheet, ActiveWindow, ActiveWorkbook — активные объекты

    13-05-Excel Active.xlsm — пример к п. 13.4.1.

    Cвойства, имена которых начинаются с Active, позволяют обращаться к различным активным объектам.

    ActiveCell возвращает объект типа Range, который представляет собой активную (выделенную) ячейку рабочего листа, отображаемого в данный момент на экране. Если при вызове этого свойства на экране нет открытого листа — произойдет ошибка.

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

    MsgBox ("В ячейке с именем " + Application.ActiveCell.Address + " хранится значение " + &  Application.ActiveCell.Value)
    ActiveCell.Value = InputBox("Введите новое значение для ячейки " + ActiveCell.Address)


    Листинг
    13.6.
    Работа с активной ячейкой

    Очевидно, что свойство Value объекта ActiveCell содержит данные, которые записаны в ячейку, а свойство Address — адрес ячейки.

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

    • ActiveChart — к активной диаграмме.
    • ActivePrinter — к активному принтеру.
    • ActiveSheet — к активному листу. Это свойство очень часто используется на практике. Например, листинг 7.7. позволяет вывести имя активного листа.

      MsgBox Application.ActiveSheet.Name
      ActiveWindow - к активному окну.
      ActiveWorkbook - к активной рабочей книге.


      Листинг
      7.7.
      Выводим имя активного листа

    13.4.2. Cells, Columns, Rows, Sheets, Workbooks, Worksheets, Names — наборы объектов и коллекции

    Эти свойства возвращают соответствующие наборы объектов и коллекции. Подробности о них мы рассмотрим ниже, здесь лишь определим их основное предназначение.

    • Cells, Columns, Rows — возвращают наборы объектов Range, содержащие, соотвественно, ячейки, столбцы, строки. При вызове этих свойств можно указывать, какие именно объекты нужно возвратить, а можно, вызвав без параметров, получить все объекты нужного вида.
    • Sheets, Worksheets — возвращают коллекции, которые содержат листы активной книги. В коллекции Sheets будут содержаться листы, которые содержат диаграммы и обычные листы, а в коллекции Worksheets — лишь обычные листы.
    • Workbooks — возвращает коллекцию открытых книг.
    • Names — возвращает коллекцию именованных диапазонов — с ними можно работать так же, как с закладками в MS Word.

    13.4.3. Range — ячейка или группа ячеек

    Возвращает объект Range, который ссылается на ячейку или группу ячеек. Это — один из важнейших объектов для работы с ячейками — ниже мы остановимся на нем подробнее.

    13.4.4. ScreenUpdating — обновление экрана

    13-06-Application ScreenUpdating.xlsm — пример к п. 13.4.4.

    Позволяет включать (присвоением свойству True ) и отключать (присвоением False ) обновление экрана. Имеет смысл отключить обновление экрана перед теми частями программы, которые интенсивно пользуются данными на листе. Благодаря тому, что системные ресурсы не будут тратиться на обновление экрана, программа будет работать быстрее. Этот метод весьма актуален, так как MS Excel часто используют для проведения ресурсоемких расчетов.

    Практика показывает, что если программа интенсивно использует вывод на экран в процессе работы, если она изменяет данные, которые участвуют в расчете формул, расположенных на листе, то отключение вывода может ускорить работу в 3-10 раз.

    Например, ниже (листинг 13.8.) приведен код, который два раза повторяет процедуру 100-кратного вывода на экран 400 целых случайных чисел и выводит время, требующееся для выполнения этих действий с обновлением экрана и без него.

    'Массив для значений времени
        Dim WorkTime(2)
        'Время начала теста
        Dim StartTime
        'Время окончания теста
        Dim StopTime
        'Включаем обновление
        Application.ScreenUpdating = True
        For i = 1 To 2
            'Во втором проходе цикла
            'выключим обновление
            If i = 2 Then _
                Application.ScreenUpdating = False
            End If
            'Запишем текущее время
            StartTime = Time
            'Перейдем на лист для теста
            Worksheets("Тест скорости").Activate
            'Выведем 100 раз целые случайные
            'числа в область 20х20
            For y = 1 To 100
                For p = 1 To 20
                    For j = 1 To 20
                        ActiveSheet.Cells(p, j) = _
                            Int(Rnd * 100)
                    Next j
                Next p
            Next y
            'Запишем время окончания
            StopTime = Time
            'Для корректного представления
            'в виде секунд
            WorkTime(i) = _
                (StopTime - StartTime) * 24 * 60 * 60
        Next i
        Application.ScreenUpdating = True
        MsgBox "Время выполнения программы." & Chr(13) + _
            "При включенном обновлении: " & _
            Round(WorkTime(1),2) & " сек." & Chr(13) & _
            "При выключенном обновлении: " & _
            Round(WorkTime(2),2) & " сек."


    Листинг
    13.8.
    Оценка скорости работы с обновлением экрана и без него

    13.4.5. Selection — ссылка на выделенный объект

    Это очень важное свойство возвращает ссылку на выделенный объект. Чаще всего это — ячейка или группа ячеек. Например, это свойство удобно использовать при работе с выделенным диапазоном ячеек (или отдельной выделенной ячейкой). Ниже мы коснемся его подробнее.

    13.4.6. WorksheetFunction — формулы Excel в коде VBA

    Возвращает объект WorksheetFunction, методы которого представляют собой формулы Excel, которые можно использовать в коде VBA. Использование этого свойства позволяет облегчить выполнение сложных расчетов.

    13.5. События Application

    13-07-Excel Application Events.xlsm — пример к п. 13.5.

    Объект Excel.Application поддерживает множество событий. Работа с ними аналогична работе с событиями Word.Application, которыми мы занимались в соответствующем разделе предыдущей главы.

    Рассмотрим основные шаги, которые необходимо произвести, чтобы работать с событиями приложения, перечислим события и приведем пример.

    Создайте новый модуль класса. Добавьте в него объявление объекта типа Excel.Application с событиями (листинг 13.9.).

    Public WithEvents obj_ExApp As Excel.Application


    Листинг
    13.9.
    Объявляем новый объект типа Excel.Application с событиями

    После этого в списке объектов редактора кода модуля появится объект obj_ExApp, а в списке событий — соответствующие ему события. Выберите нужное вам событие — автоматически будет создан обработчик для него. В частности, Excel.Application поддерживает следующие события:

    • NewWorkbook — происходит при создании новой книги
    • SheetActivate — при активации любого листа
    • SheetBeforeDoubleClick — происходит при двойном щелчке по листу, то есть позволяет перехватить щелчок и выполнить собственную процедуру до того, как будет выполнено стандартное действие.
    • SheetBeforeRightClick — позволяет перехватить нажатие правой кнопки мыши по листу.
    • SheetCalculate — после пересчета листа или после изменения данных, которые отображаются на диаграмме.
    • SheetChange — при изменении содержимого ячеек на любом листе.
    • SheetFollowHyperlink — происходит при переходе по гиперссылке, которая может быть включена в лист Microsoft Excel.
    • SheetSelectionChange — при изменении выделения на листе
    • WindowActivate — при активации окна книги.
    • WindowDeactivate — при деактивации окна книги.
    • WindowResize — при изменении размера окна книги.
    • WorkbookActivate — при активации книги.
    • WorkbookBeforeClose — перед закрытием книги.
    • WorkbookBeforePrint — перед печатью книги.
    • WorkbookBeforeSave — перед сохранением книги.
    • WorkbookDeactivate — при деактивации книги.
    • WorkbookNewSheet — при добавлении нового листа в любую из открытых книг.
    • WorkbookOpen — при открытии книги.

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

    Итак, вот (листинг 13.10.) код процедуры, который связывает объект созданного нами класса AppEvents с приложением:

    Dim obj_ExcelAppEv As New AppEvents
    Sub EventsInit()
        Set obj_ExcelAppEv.obj_ExApp = Excel.Application
    End Sub


    Листинг
    13.10.
    Связываем объект с приложением

    А вот (листинг 13.11.) полный код модуля класса AppEvents с объявлением объектной переменной и обработчиком события.

    Public WithEvents obj_ExApp As Excel.Application
    Private Sub obj_ExApp_NewWorkbook(ByVal Wb As Workbook)
        'Выполняется при создании новой книги
        MsgBox "Вы создали новую книгу"
    End Sub


    Листинг
    13.11.
    Код модуля класса с обработчиком события

    13.6. Выводы

    В этой лекции мы обсудили методы, свойства и события объекта Application приложения Microsoft Excel. Можно заметить, что некоторые из этих методов прямо указывают на то, что Excel — это приложение, рассчитанное на проведение достаточно серьезных расчетов. В следующей лекции мы рассмотрим особенности работы с документами MS Excel.

    Понравилась статья? Поделить с друзьями:
  • Vba and excel and count rows
  • Vba excel activecell свойства
  • Vba and excel 2016
  • Vba excel active cell
  • Vba excel access примеры