End vba excel описание

Свойство End объекта Range применяется для поиска первых и последних заполненных ячеек в VBA Excel — аналог сочетания клавиш Ctrl+стрелка.

Свойство End объекта Range возвращает объект Range, представляющий ячейку в конце или начале заполненной значениями области исходного диапазона по строке или столбцу в зависимости от указанного направления. Является в VBA Excel программным аналогом сочетания клавиш — Ctrl+стрелка (вверх, вниз, вправо, влево).

Возвращаемая свойством Range.End ячейка в зависимости от расположения и содержания исходной:

Исходная ячейка Возвращаемая ячейка
Исходная ячейка пустая Первая заполненная ячейка или, если в указанном направлении заполненных ячеек нет, последняя ячейка строки или столбца в заданном направлении.
Исходная ячейка не пустая и не крайняя внутри исходного заполненного диапазона в указанном направлении Последняя заполненная ячейка исходного заполненного диапазона в указанном направлении
Исходная ячейка не пустая, но в указанном направлении является крайней внутри исходного заполненного диапазона Первая заполненная ячейка следующего заполненного диапазона или, если в указанном направлении заполненных ячеек нет, последняя ячейка строки или столбца в заданном направлении.

Синтаксис

Expression.End (Direction)

Expression — выражение (переменная), представляющее объект Range.

Параметры

Параметр Описание
Direction Константа из коллекции XlDirection, задающая направление перемещения. Обязательный параметр.

Константы XlDirection:

Константа Значение Направление
xlDown -4121 Вниз
xlToLeft -4159 Влево
xlToRight -4161 Вправо
xlUp -4162 Вверх

Примеры

Скриншот области рабочего листа для визуализации примеров применения свойства Range.End:

Примеры возвращаемых ячеек свойством End объекта Range("C10") с разными значениями параметра Direction:

Выражение с Range.End Возвращенная ячейка
Set myRange = Range("C10").End(xlDown) Range("C16")
Set myRange = Range("C10").End(xlToLeft) Range("A10")
Set myRange = Range("C10").End(xlToRight) Range("E10")
Set myRange = Range("C10").End(xlUp) Range("C4")

Пример возвращения заполненной значениями части столбца:

Sub Primer()

Dim myRange As Range

Set myRange = Range(Range(«C10»), Range(«C10»).End(xlDown))

MsgBox myRange.Address  ‘Результат: $C$10:$C$16

End Sub


Excel VBA End

VBA END Function

End Statement is almost used in every other programming language, so VBA is also not different from it. Every code has a start and has an end for it. How do we end any specific function or code is different in programming languages. In VBA we close our code by using END Statement. But apart from this end statement, we have another end function in VBA which is used to refer to the cells of a worksheet which we will talk about detail in this article.

As I have told above we will be discussing another property of END in VBA which is used to refer to the end of the cells. There are many separate properties for this  END function. For example, end to the right or end the left or end to the bottom. To make this more clear look at below the image.

VBA End Example 1.1

In Excel worksheet how do we move from cell A1 which points A to cell E1 which is point B? We press CTRL + right arrow. Similarly to move from point B to point C we press CTRL + Down Arrow and from point C to point D we press CTRL + Left arrow. Similarly for point D to point A we press CTRL + Up arrow.

This is also known as to refer to the next cell which has some value in it. This process skips the blank cells and moves to the end of the reference. In VBA we do not press CTRL + Right Arrow to move from point A to point B. We use properties of END to do this. And this is what we will learn in this article. How can we move from Point A to End to the right which is point B and select the cell range and do the same for others.

How to Use VBA End Function in Excel?

We will learn how to use a VBA END Function with example in excel.

You can download this VBA END Excel Template here – VBA END Excel Template

Let us learn to do so by a few examples.

Example #1 – VBA END

In the first example let us select cell E1 using the end property in VBA.

Step 1: From the Insert tab insert a new module. Remember we will work in the same module for the entire article. We can see the module in the project window, Open the module as shown below.

Module

Step 2: Start the Sub procedure in the window.

Code:

Sub sample()

End Sub

VBA End Example 1.2

Step 3: Now we know that we have to move from cell A1 to cell E1 so type the following code.

Code:

Sub sample()

Range ("A1")

End Sub

VBA End Example 1.3

Step 4: Now put a dot after the parenthesis and write end as shown below.

Code:

Sub sample()

Range("A1").End

End Sub

Example 1.4

Step 5: Press Enter and open a parenthesis we will see some more options in the end statement as follows,

Code:

Sub sample()

Range("A1").End(

End Sub

Example 1.5

Step 6: Select XltoRight as we have to move right to select cell E1.

Code:

Sub sample()

Range("A1").End (xlToRight)

End Sub

Example 1.6

Step 7: Now to select the range, put a dot after the closing parenthesis and write select as shown below.

Code:

Sub sample()

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

End Sub

VBA End Example 1.7

Step 8: Now let us execute the code written above and see the result in sheet 1 as follows.

VBA End 1

From Point A which is cell A1 we moved to the end of the data in the right which is cell E1.

Example #2 – VBA END

Similar to the above example where we moved right from the cell A1 we can move left too. Let us select cell A5 which is point C from Point D.

Step 1: In the same module, declare another subprocedure for another demonstration.

Code:

Sub Sample1()

End Sub

VBA End Example 2.1

Step 2: Now let us move from cell E5 to cell A5, so first refer to cell E5 as follows.

Code:

Sub Sample1()

Range ("E5")

End Sub

VBA End Example 2.2

Step 3: Now let us move to the left of the cell E5 using the end statement.

Code:

Sub Sample1()

Range("E5").End (xlToLeft)

End Sub

Example 2.3

Step 4: Now to select cell A5 put a dot after the parenthesis and write select.

Code:

Sub Sample1()

Range("E5").End(xlToLeft).Select

End Sub

Example 2.4

Step 5: Now execute this code above and see the result in sheet 1 as follows.

VBA End 3

From point C we moved to point D using the end statement.

Example #3 – VBA END

Now let use the downwards end statement which means we will select cell A5 from cell A1.

Step 1: In the same module, declare another subprocedure for another demonstration.

Code:

Sub Sample2()

End Sub

VBA End Example 3.1

Step 2: Now let us move from cell A5 to cell A1, so first refer to cell A1 as follows.

Code:

Sub Sample2()

Range ("A1")

End Sub

VBA End Example 3.2

Step 3: Now let us move to the down of the cell A1 using the end statement.

Code:

Sub Sample2()

Range("A1").End (xlDown)

End Sub

Example 3.3

Step 4: Now to select cell A5 put a dot after the parenthesis and write select.

Code:

Sub Sample2()

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

End Sub

Example 3.4

Step 5: Now execute this code above and see the result in sheet 1 as follows.

VBA End 4

We have moved from Point A to point D using the down property of the end statement.

Example #4 – VBA END

Now let us select the total range from Point A to Point B to Point C and to Point D using the end statement.

Step 1: In the same module, declare another subprocedure for another demonstration.

Code:

Sub FinalSample()

End Sub

VBA End Example 4.1

Step 2: Now let us select from cell A1 to cell E5, so first refer to cell A1 as follows.

Code:

Sub FinalSample()

Range("A1"

End Sub

VBA End Example 4.2

Step 3: Now let us move down of the cell A1 using the end statement.

Code:

Sub FinalSample()

Range("A1", Range("A1").End(xlDown)

End Sub

Example 4.3

Step 4: Now we need to move to the right of the cell A1 by using the following end statement as follows.

Code:

Sub FinalSample()

Range("A1", Range("A1").End(xlDown).End(xlToRight))

End Sub

Example 4.4

Step 5: Select the cell range using the select statement.

Code:

Sub FinalSample()

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

End Sub

VBA End Example 4.4

Step 6: Let us run the above code and see the final result in sheet 1 as follows.

VBA End

Things to Remember

  • The method to use END in VBA Excel to refer cells is very easy. We refer to a range first
  • Range( Cell ) and then we use End property to select or go to the last used cell in the left-right or down of the reference cell
  • Range (Cell).End(XltoRight) to got to the right of the cell.
  • First things which we need to remember is END property is different to the ending of a procedure or a function in VBA.
  • We can use a single property to refer to a cell i.e. to right or left of it or we can select the whole range together.
  • In a worksheet, we use the same reference using the CTRL button but in VBA we use the END statement.

Recommended Articles

This is a guide to VBA END. Here we discuss how to use Excel VBA END Function along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA InStr
  2. VBA Integer
  3. VBA ISNULL
  4. VBA Transpose

Return to VBA Code Examples

This tutorial will show you how to use the Range.End property in VBA.

Most things that you do manually in an Excel workbook or worksheet can be automated in VBA code.

If you have a range of non-blank cells in Excel, and you press Ctrl+Down Arrow, your cursor will move to the last non-blank cell in the column you are in.  Similarly, if you press Ctrl+Up Arrow, your cursor will move to the first non-blank cell.   The same applies for a row using the Ctrl+Right Arrow or Ctrl+Left Arrow to go to the beginning or end of that row.  All of these key combinations can be used within your VBA code using the End Function.

Range End Property Syntax

The Range.End Property allows you to move to a specific cell within the Current Region that you are working with.

expression.End (Direction)

the expression is the cell address (Range) of the cell where you wish to start from eg: Range(“A1”)

END is the property of the Range object being controlled.

Direction is the Excel constant that you are able to use.  There are 4 choices available – xlDown, xlToLeft, xlToRight and xlUp.

vba end eigenschaft syntax

Moving to the Last Cell

The procedure below will move you to the last cell in the Current Region of cells that you are in.

Sub GoToLast()
'move to the last cell occupied in the current region of cells
   Range("A1").End(xlDown).Select
End Sub

Counting Rows

The following procedure allows you to use the xlDown constant with the Range End property to count how many rows are in your current region.

Sub GoToLastRowofRange()
   Dim rw As Integer
   Range("A1").Select
'get the last row in the current region
   rw = Range("A1").End(xlDown).Row
'show how many rows are used
   MsgBox "The last row used in this range is " & rw
End Sub

While the one below will count the columns in the range using the xlToRight constant.

Sub GoToLastCellofRange() 
   Dim col As Integer 
   Range("A1").Select 
'get the last column in the current region
   col = Range("A1").End(xlToRight).Column
'show how many columns are used
   MsgBox "The last column used in this range is " & col
 End Sub

Creating a Range Array

The procedure below allows us to start at the first cell in a range of cells, and then use the End(xlDown) property to find the last cell in the range of cells.  We can then ReDim our array with the total rows in the Range, thereby allowing us to loop through the range of cells.

Sub PopulateArray()
'declare the array
   Dim strSuppliers() As String
'declare the integer to count the rows
   Dim n As Integer
'count the rows
   n = Range("B1", Range("B1").End(xlDown)).Rows.Count
'initialise and populate the array
   ReDim strCustomers(n)
'declare the integer for looping
   Dim i As Integer
'populate the array
   For i = 0 To n
     strCustomers(i) = Range("B1").Offset(i, 0).Value
   Next i
'show message box with values of array
   MsgBox Join(strCustomers, vbCrLf)
End Sub

When we run this procedure, it will return the following message box.

vba end array

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!
vba save as

Learn More!

End Function in VBA

An End is a statement in VBA that has multiple forms in VBA applications. One can put a simple End statement anywhere in the code. It will automatically stop the execution of the code. One can use the End statement in many procedures like to end the sub procedure or to end any Loop function like “End If.”

For everything, there is an end. In VBA, it is no different. You must have seen the word “End” in all the codes in your VBA. We can End in “End Sub,” “End Function,” and “End If.” These are common as we know each “End” suggests the end of the procedure. These VBA End statements do not require any special introduction because we are familiar with them in our 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.

Apart from the above “End,” we have one property, “End,” in VBA. This article will take you through that property and how to use it in our coding.

Table of contents
  • End Function in VBA
    • End Property in VBA
    • Examples of Excel VBA End Function
      • Example #1 – Use VBA End Property To Move in Worksheet
      • Example #2 – Selection Using End Property
      • Example #3 – Select Right to Left, Right to Bottom, & Top
    • Recommended Articles

VBA End

End Property in VBA

The “End” is the property we use in VBA to move in the suggested direction. The typical example of direction is moving from the active cell to the last used cell or the last entry cell horizontally and vertically in the worksheet.

For example, let us recall this with a worksheet. Look at the below image.

VBA End Example 1

Right now, we are in the A1 cell.

If we want to move to the last used cell horizontally, we use the excel shortcut keyAn Excel shortcut is a technique of performing a manual task in a quicker way.read more Ctrl + Right Arrow, which will take us to the last used cell horizontally.

VBA End Example 1-1

Similarly, if we want to move to the last used cell downwards or vertically, we press the shortcut key Ctrl + Down Arrow.

VBA End Example 1-2

So, to move from left to right, we press Ctrl + Left Arrow. To move from bottom to top, we press Ctrl + Up Arrow.

A similar thing can be done in VBA but not by using the Ctrl key. Rather, we need to use the word “End.”

Examples of Excel VBA End Function

You can download this VBA End Excel Template here – VBA End Excel Template

Example #1 – Use VBA End Property To Move in Worksheet

Let us look at how to use Excel VBA End to move in the sheet. First, we need to decide which cell we need to move. For example, suppose we need to move from cell A1, so refer to the cell using the VBA Range objectRange is a property in VBA that helps specify a particular cell, a range of cells, a row, a column, or a three-dimensional range. In the context of the Excel worksheet, the VBA range object includes a single cell or multiple cells spread across various rows and columns.read more.

Code:

Sub End_Example1()

  Range ("A1")

End Sub

VBA End Example 2

Put dot (.) to see the IntelliSense list. Then, select “End” VBA property from the list.

Code:

Sub End_Example1()

  Range("A1").End

End Sub

VBA End Example 2-1

Once the end property is selected, open parenthesis.

Code:

Sub End_Example1()

  Range("A1").End(

End Sub

VBA End Example 2-2

As soon as you open parenthesis, we can see all the available options with the “End” property. Select “xlToRight” to move horizontally from cell A1 to the last used cell.

Code:

Sub End_Example1()

  Range("A1").End (xlToRight)

End Sub

VBA End Example 2-3

After moving to the last cell, we must select what we need to do. Put dot (.) to see the IntelliSense list.

Code:

Sub End_Example1()

  Range("A1").End(xlToRight).

End Sub

VBA End Example 2-4

Choose the “Select” method from the IntelliSense list.

Code:

Sub End_Example1()

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

End Sub

VBA End Example 2-5

It will make use of cell A1 to last used cells horizontally.

VBA End Example 2-6

Similarly, use the other three options to move right, left, down, and up.

To move right from cell A1.

Code:

Sub End_Example1()

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

End Sub

To move down from cell A1.

Code:

Sub End_Example1()

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

End Sub

To move up from cell A5.

Code:

Sub End_Example1()

  Range("A5").End(xlUp).Select

End Sub

To move left from cell D1.

Code:

Sub End_Example1()

  Range("D1").End(xlToLeft).Select

End Sub

All the above codes are examples of using the “End” property to move in the worksheet.

We will now see how to select the ranges using the “End” property.

Example #2 – Selection Using End Property

We need to end the property to select the range of cells in the worksheet. For this example, consider the below data.

VBA End Example 3

Select A1 to Last Used Cell

To select the cells from A1 to the last used cell horizontally, first, mention cell A1 in the Range object.

Code:

Sub End_Example2()

  Range("A1",

End Sub

VBA End Example 3-1

For the second argument, open one more Range object and mention the cell as A1 only.

Code:

Sub End_Example2()

  Range("A1",Range("A1")

End Sub

Example 3-2

Close only one bracket and put a dot to select the Excel VBA End property.

Code:

Sub End_Example2()

  Range("A1",Range("A1").End(

End Sub

Example 3-3

Now, select xlToRight and close two brackets.

Code:

Sub End_Example2()

  Range("A1",Range("A1").End(xlToRight))

End Sub

Example 3-4

Now, choose the “Select” method.

Code:

Sub End_Example2()

  Range("A1", Range("A1").End(xlToRight)).Select

End Sub

Example 3-5

We have completed it now.

Run this code to see the impact.

Example 3-6

As you can see, it has selected the range A1 to D1.

Similarly, to select downwards, use the below code.

Code:

Sub End_Example2()

  Range("A1", Range("A1").End(xlDown)).Select
     'To select from left to right
End Sub

Code:

Sub End_Example2()

  Range("A1", Range("A1").End(xlDown)).Select
     'To select from top to down
End Sub

Code:

Sub End_Example2()

  Range("D1", Range("D1").End(xlToLeft)).Select
     'To select from right to left
End Sub

Code:

Sub End_Example2()

  Range("A5", Range("A5").End(xlUp)).Select
     'To select from bottom to up
End Sub

Example #3 – Select Right to Left, Right to Bottom, & Top

We have seen how to select horizontally and vertically. Next, we need to use two “End” properties to select vertically and horizontally. For example, to select the data from A1 to D5, we need to use the below code.

Code:

Sub End_Example3()

 Range("A1", Range("A1").End(xlDown).End(xlToRight)).Select
  'To from cell A1 to last use cell downwards & rightwards
End Sub

It will select the complete range like the one below.

Example 4

Like this, we can use the VBA “End” function property to select a range of cells.

Recommended Articles

This article has been a guide to the Excel VBA End function. Here, we learn how to use End property in VBA and End property selection, examples, and a downloadable template. Below are some useful Excel articles related to VBA: –

  • VBA Split
  • Call Sub in Excel
  • Today in VBA
  • How to Paste in VBA?

Содержание

  1. Оператор End
  2. Синтаксис
  3. Замечания
  4. Пример
  5. См. также
  6. Поддержка и обратная связь
  7. Свойство Range.End (Excel)
  8. Синтаксис
  9. Параметры
  10. Пример
  11. Поддержка и обратная связь
  12. Range.End property (Excel)
  13. Syntax
  14. Parameters
  15. Example
  16. Support and feedback
  17. End statement
  18. Syntax
  19. Remarks
  20. Example
  21. See also
  22. Support and feedback
  23. VBA Range.End (xlDown, xlUp, xlToRight, xlToLeft)
  24. Range End Property Syntax
  25. Moving to the Last Cell
  26. Counting Rows
  27. Creating a Range Array
  28. VBA Coding Made Easy
  29. VBA Code Examples Add-in

Оператор End

Заканчивает процедуру или блок.

Синтаксис

End
End Function
End If
End Property
End Select
End Sub
End Type
End With

Синтаксис оператора End состоит из следующих форм:

Statement Описание
End Сразу же прекращает выполнение. Никогда не требуется сам по себе, но может быть размещен в любом месте процедуры для завершения выполнения кода, закрытия файлов, открытых с помощью инструкции Open , и для очистки переменных.
End Function Требуется для завершения инструкции Function .
End If Требуется для завершения блока Если. Затем. Оператор Else .
End Property Требуется для завершения процедуры Property Let, Property Get или Property Set .
End Select Требуется для завершения инструкции Select Case .
End Sub Требуется для завершения инструкции Sub .
End Type Требуется для завершения определения определяемого пользователем типа (оператор Type ).
End With Требуется для завершения инструкции With .

Замечания

При выполнении оператор End сбрасывает все переменные на уровне модуля и все статические локальные переменные во всех модулях. Чтобы сохранить значение этих переменных, используйте вместо этого инструкцию Stop . Вы сможет затем возобновить выполнение, сохранив значение этих переменных.

Оператор End резко останавливает выполнение кода, не вызывая событие Unload, QueryUnload или Terminate или любой другой код Visual Basic. Код, помещенный в события Unload, QueryUnload и Terminate форм и модулей класса, не выполняется. Объекты, созданные из модулей класса, уничтожаются, файлы, открытые с помощью инструкции Open , закрываются, а память, используемая программой, освобождается. Ссылки на объекты, удерживаемые другими программами, становятся недопустимыми.

Оператор End предоставляет способ заставить программу остановиться. Для нормального прекращения работы программы Visual Basic следует выгрузить все формы. Программа закроется, как только не будет других программ, удерживающих ссылки на объекты, созданные из модулей открытого класса, и не будет выполняться код.

Пример

В этом примере оператор End используется для завершения выполнения кода, если пользователь вводит недопустимый пароль.

См. также

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

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

Источник

Свойство Range.End (Excel)

Возвращает объект Range, представляющий ячейку в конце области, содержащей исходный диапазон. Эквивалентно нажатию клавиш END+СТРЕЛКА ВВЕРХ, END+СТРЕЛКА ВНИЗ, END+СТРЕЛКА ВЛЕВО или END+СТРЕЛКА ВПРАВО. Объект Range предназначен только для чтения.

Синтаксис

выражение.End (Direction)

выражение: переменная, представляющая объект Range.

Параметры

Имя Обязательный или необязательный Тип данных Описание
Direction Обязательный XlDirection Направление перемещения.

Пример

В этом примере выделяется ячейка в верхней части столбца B в области, содержащей ячейку B4.

В этом примере выделяется ячейка в конце строки 4 в области, содержащей ячейку B4.

В этом примере расширяется выделенный фрагмент с ячейки B4 до последней ячейки в строке 4, содержащей данные.

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

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

Источник

Range.End property (Excel)

Returns a Range object that represents the cell at the end of the region that contains the source range. Equivalent to pressing END+UP ARROW, END+DOWN ARROW, END+LEFT ARROW, or END+RIGHT ARROW. Read-only Range object.

Syntax

expression.End (Direction)

expression A variable that represents a Range object.

Parameters

Name Required/Optional Data type Description
Direction Required XlDirection The direction in which to move.

Example

This example selects the cell at the top of column B in the region that contains cell B4.

This example selects the cell at the end of row 4 in the region that contains cell B4.

This example extends the selection from cell B4 to the last cell in row four that contains data.

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.

Источник

End statement

Ends a procedure or block.

Syntax

End
End Function
End If
End Property
End Select
End Sub
End Type
End With

The End statement syntax has these forms:

Statement Description
End Terminates execution immediately. Never required by itself but may be placed anywhere in a procedure to end code execution, close files opened with the Open statement, and to clear variables.
End Function Required to end a Function statement.
End If Required to end a block If…Then…Else statement.
End Property Required to end a Property Let, Property Get, or Property Set procedure.
End Select Required to end a Select Case statement.
End Sub Required to end a Sub statement.
End Type Required to end a user-defined type definition (Type statement).
End With Required to end a With statement.

When executed, the End statement resets all module-level variables and all static local variables in all modules. To preserve the value of these variables, use the Stop statement instead. You can then resume execution while preserving the value of those variables.

The End statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events of forms and class modules is not executed. Objects created from class modules are destroyed, files opened by using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.

The End statement provides a way to force your program to halt. For normal termination of a Visual Basic program, you should unload all forms. Your program closes as soon as there are no other programs holding references to objects created from your public class modules and no code executing.

Example

This example uses the End statement to end code execution if the user enters an invalid password.

See also

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.

Источник

VBA Range.End (xlDown, xlUp, xlToRight, xlToLeft)

In this Article

This tutorial will show you how to use the Range.End property in VBA.

Most things that you do manually in an Excel workbook or worksheet can be automated in VBA code.

If you have a range of non-blank cells in Excel, and you press Ctrl+Down Arrow, your cursor will move to the last non-blank cell in the column you are in. Similarly, if you press Ctrl+Up Arrow, your cursor will move to the first non-blank cell. The same applies for a row using the Ctrl+Right Arrow or Ctrl+Left Arrow to go to the beginning or end of that row. All of these key combinations can be used within your VBA code using the End Function.

Range End Property Syntax

The Range.End Property allows you to move to a specific cell within the Current Region that you are working with.

expression.End (Direction)

the expression is the cell address (Range) of the cell where you wish to start from eg: Range(“A1”)

END is the property of the Range object being controlled.

Direction is the Excel constant that you are able to use. There are 4 choices available – xlDown, xlToLeft, xlToRight and xlUp.

Moving to the Last Cell

The procedure below will move you to the last cell in the Current Region of cells that you are in.

Counting Rows

The following procedure allows you to use the xlDown constant with the Range End property to count how many rows are in your current region.

While the one below will count the columns in the range using the xlToRight constant.

Creating a Range Array

The procedure below allows us to start at the first cell in a range of cells, and then use the End(xlDown) property to find the last cell in the range of cells. We can then ReDim our array with the total rows in the Range, thereby allowing us to loop through the range of cells.

When we run this procedure, it will return the following message box.

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!

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.

Источник

Понравилась статья? Поделить с друзьями:
  • End sections in word
  • End of word перевод на русском
  • End of word document with
  • End of the word video
  • End of the word today