Vba excel массивы ubound

Массивы в VBA Excel: одномерные, многомерные и динамические. Объявление и использование массивов. Операторы Public, Dim и ReDim. Функции Array, LBound, UBound.

Массивы – это множества однотипных элементов, имеющих одно имя и отличающиеся друг от друга индексами. Они могут быть одномерными (линейными), многомерными и динамическими. Массивы в VBA Excel, как и другие переменные, объявляются с помощью операторов Dim и Public. Для изменения размерности динамических массивов используется оператор ReDim. Массивы с заранее объявленной размерностью называют статическими.

Одномерные массивы

Объявление одномерных (линейных) статических массивов в VBA Excel:

Public Massiv1(9) As Integer

Dim Massiv2(1 To 9) As String

В первом случае публичный массив содержит 10 элементов от 0 до 9 (нижний индекс по умолчанию — 0, верхний индекс — 9), а во втором случае локальный массив содержит 9 элементов от 1 до 9.

По умолчанию VBA Excel считает в массивах нижним индексом нуль, но, при желании, можно сделать нижним индексом по умолчанию единицу, добавив в самом начале модуля объявление «Option Base 1».

Многомерные массивы

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

‘Массив двухмерный

Public Massiv1(3, 6) As Integer

‘Массив трехмерный

Dim Massiv2(1 To 6, 1 To 8, 1 To 5) As String

‘Массив четырехмерный

Dim Massiv3(9, 9, 9, 9) As Date

Третий массив состоит из 10000 элементов — 10×10×10×10.

Динамические массивы

Динамические массивы в VBA Excel, в отличие от статических, объявляются без указания размерности:

Public Massiv1() As Integer

Dim Massiv2() As String

Такие массивы используются, когда заранее неизвестна размерность, которая определяется в процессе выполнения программы. Когда нужная размерность массива становится известна, она в VBA Excel переопределяется с помощью оператора ReDim:

Public Massiv1() As Integer

Dim Massiv2() As String

ReDim Massiv1(1 To 20)

ReDim Massiv2(3, 5, 4)

При переопределении размерности массива вместо верхнего индекса можно использовать переменную:

Dim Massiv1() as Variant, x As Integer

x = 20

ReDim Massiv1(1 To x)

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

С помощью оператора ReDim невозможно изменить обычный массив, объявленный с заранее заданной размерностью. Попытка переопределить размерность такого массива вызовет ошибку компиляции с сообщением: Array already dimensioned (Массив уже измерен).

При переопределении размерности динамических массивов в VBA Excel теряются значения их элементов. Чтобы сохранить значения, используйте оператор Preserve:

Dim Massiv1() As String

операторы

ReDim Massiv1(5, 2, 3)

операторы

ReDim Preserve Massiv1(5, 2, 7)

Обратите внимание!
Переопределить с оператором Preserve можно только последнюю размерность динамического массива. Это недоработка разработчиков, которая сохранилась и в VBA Excel 2016. Без оператора Preserve можно переопределить все размерности.

Максимальный размер

Размер массива – это произведение длин всех его измерений. Он представляет собой общее количество элементов, содержащихся в данный момент в массиве.

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

Использование массивов

Приведу два примера, где не обойтись без массивов.

1. Как известно, функция Split возвращает одномерный массив подстрок, извлеченных из первоначальной строки с разделителями. Эти данные присваиваются заранее объявленному строковому (As String) одномерному динамическому массиву. Размерность устанавливается автоматически в зависимости от количества подстрок.

2. Данные в массивах обрабатываются значительно быстрее, чем в ячейках рабочего листа. Построчную обработку информации в таблице Excel можно наблюдать визуально по мерцаниям экрана, если его обновление (Application.ScreenUpdating) не отключено. Чтобы ускорить работу кода, можно значения из диапазона ячеек предварительно загрузить в динамический массив с помощью оператора присваивания (=). Размерность массива установится автоматически. После обработки данных в массиве кодом VBA полученные результаты выгружаются обратно на рабочий лист Excel. Обратите внимание, что загрузить значения в диапазон ячеек рабочего листа через оператор присваивания (=) можно только из двумерного массива.

Функции Array, LBound, UBound

Функция Array

Функция Array возвращает массив элементов типа Variant из первоначального списка элементов, перечисленных через запятую. Нумерация элементов в массиве начинается с нуля. Обратиться к элементу массива можно, указав в скобках его номер (индекс).

Sub Test1()

Dim a() As Variant

a = Array(«text», 25, «solo», 35.62, «stop»)

MsgBox a(0) & vbNewLine & a(1) & vbNewLine _

& a(2) & vbNewLine & a(3) & vbNewLine & a(4)

End Sub

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

Функция LBound

Функция LBound возвращает значение типа Long, равное наименьшему (нижнему) доступному индексу в указанном измерении массива.
Синтаксис:
LBound (arrayname[, dimension])

  • arrayname — это имя переменной массива, является обязательным аргументом;
  • dimension — это номер измерения массива, необязательный аргумент, по умолчанию принимает значение 1.

Наименьший индекс по-умолчанию может быть равен 0 или 1 в зависимости от настроек оператора Option Base. Нижняя граница архива, полученного с помощью функции Array, всегда равна 0.

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

Функция UBound

Функция UBound возвращает значение типа Long, равное наибольшему (верхнему) доступному индексу в указанном измерении массива.
Синтаксис:
UBound( arrayname[, dimension])

  • arrayname — это имя переменной массива, является обязательным аргументом;
  • dimension — это номер измерения массива, необязательный аргумент, по умолчанию принимает значение 1.

Функция UBound используется вместе с функцией LBound для определения размера массива.

Sub Test2()

Dim a(2 To 53) As String

MsgBox «Наименьший индекс = « & LBound(a) & _

vbNewLine & «Наибольший индекс = « & UBound(a)

End Sub

Скопируйте код в модуль VBA Excel и запустите его на выполнение. Информационное сообщение MsgBox покажет значения наименьшего и наибольшего индекса переменной массива a.

Обход массива циклом

Обход одномерного массива циклом For… Next, в котором для определения границ массива используются функции UBound и LBound:

Sub Test3()

Dim a() As Variant, i As Long

a = Array(«text», 25, «solo», 35.62, «stop»)

    For i = LBound(a) To UBound(a)

        Debug.Print «a(« & i & «) = « & a(i)

    Next

End Sub

Результат работы цикла вы увидите в окне Immediate.

Очистка (обнуление) массивов

Первый способ

Очистить любой массив, статический или динамический, без использования цикла можно с помощью оператора Erase. Термин «обнуление» можно применить только к массиву числового типа.

Dim Massiv1(4, 3) As String,  Massiv2() As Variant

операторы

‘переопределяем динамический массив

ReDim Massiv2(2, 5, 3)

операторы

‘очищаем массивы

Erase Massiv1

Erase Massiv2

Обратите внимание, что оба массива при таком способе очистки будут возвращены в исходное состояние, которое они имели сразу после объявления:

  • статический Massiv1 сохранит размерность (4, 3);
  • динамический Massiv2 не сохранит размерность ().

Второй способ

Динамический массив можно очистить (обнулить) без использования цикла с помощью оператора ReDim. Просто переопределите его с той же размерностью.

Dim Massiv() As Double

операторы

‘переопределяем массив

ReDim Massiv(5, 6, 8)

операторы

‘очищаем массив

ReDim Massiv(5, 6, 8)


Функция UBound

UBound(ArrayName[,Dimension])

Функция UBound (Upper Bound) служит для определения верхней границы (индекса самого последнего элемента) массива по заданному измерению

Возвращаемое значение

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

Параметры

Элемент Описание
ArrayName Обязательный. Имя переменной массива, соответствующее стандартным соглашениям о наименовании переменных. При задании в качестве аргумента переменной, не являющейся массивом, генерируется ошибка времени исполнения Type mismatch
Dimension Необязательный. Значение типа Variant(Long). Целое число, указывающее, для какого из измерений возвращается верхняя граница. Первому измерению соответствует 1, второму – 2 и т. д. Если параметр Dimension опущен, предполагается значение равное 1

Примечание

Функция UBound применяется совместно с функцией LBound для определения размера массива. Функция LBound используется для нахождения нижней границы для измерения массива

Пример

' Пример использования функции UBound
' Объявляем трехмерный массив
Dim myArray(1 To 100, 0 To 3, -3 To 4)
Dim retval
retval=UBound(myArray, 1) 'возвращает 100
retval=UBound(myArray, 2) 'возвращает 3
retval=UBound(myArray, 3) 'возвращает 4

Категория
Функции обработки массивов

Permalink

Cannot retrieve contributors at this time

title keywords f1_keywords ms.prod ms.assetid ms.date ms.localizationpriority

UBound function (Visual Basic for Applications)

vblr6.chm1009050

vblr6.chm1009050

office

8dda22e9-d9f9-9944-1b91-cfb8b61774a7

12/13/2018

medium

Returns a Long data type containing the largest available subscript for the indicated dimension of an array.

Syntax

UBound(arrayname, [ dimension ])

The UBound function syntax has these parts.

Part Description
arrayname Required. Name of the array variable; follows standard variable naming conventions.
dimension Optional; Variant (Long). Whole number indicating which dimension’s upper bound is returned. Use 1 for the first dimension, 2 for the second, and so on. If dimension is omitted, 1 is assumed.

Remarks

The UBound function is used with the LBound function to determine the size of an array. Use the LBound function to find the lower limit of an array dimension.

UBound returns the following values for an array with these dimensions:

Statement Return Value
UBound(A, 1) 100
UBound(A, 2) 3
UBound(A, 3) 4

Example

This example uses the UBound function to determine the largest available subscript for the indicated dimension of an array.

Dim Upper
Dim MyArray(1 To 10, 5 To 15, 10 To 20)    ' Declare array variables.
Dim AnyArray(10)
Upper = UBound(MyArray, 1)    ' Returns 10.
Upper = UBound(MyArray, 3)    ' Returns 20.
Upper = UBound(AnyArray)      ' Returns 10.

See also

  • Functions (Visual Basic for Applications)

[!includeSupport and feedback]

Return to VBA Code Examples

In this Article

  • UBound Description
  • Simple UBound Examples
  • UBound Syntax
  • Examples of Excel VBA UBound Function
  • LBound Description
  • Simple LBound Examples
  • LBound Syntax
  • Examples of Excel VBA LBound Function

UBound Description

Returns the highest subscript for a dimension of an array.

Simple UBound Examples

Sub UBound_Example()
    Dim a(3 To 10) As Integer
    MsgBox UBound(a)
End Sub

Result: 10

UBound Syntax

UBound(ArrayName, [ Dimension ])

The UBound function contains 2 arguments:

ArrayName: Name of Array variable.

Dimension: [Optional] Integer indicating which dimension’s upper bound is returned. Use 1 for the first dimension, 2 for the second, etc. 1 if ommitted.

Examples of Excel VBA UBound Function

Sub UBound_Example1()
    Dim arrValue(1 To 5, 4 To 8, 12 To 25)
    MsgBox UBound(arrValue)
    MsgBox UBound(arrValue, 1)
    MsgBox UBound(arrValue, 2)
    MsgBox UBound(arrValue, 3)
End Sub

Result: 5, 5, 8, 25

LBound Description

Returns the lowest subscript for a dimension of an array.

Simple LBound Examples

Sub LBound_Example()
    Dim a(3 To 10) As Integer
    MsgBox LBound(a)
End Sub

Result: 3

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!

automacro

Learn More

LBound Syntax

LBound(ArrayName, [ Dimension ])

The LBound function contains 2 arguments:

ArrayName: Name of Array variable.

Dimension: [Optional] Integer indicating which dimension’s lower bound is returned. Use 1 for the first dimension, 2 for the second, etc. 1 if ommitted.

Examples of Excel VBA LBound Function

Sub LBound_Example1()
    Dim arrValue(1 To 5, 4 To 8, 12 To 25)
    MsgBox LBound(arrValue)
    MsgBox LBound(arrValue, 1)
    MsgBox LBound(arrValue, 2)
    MsgBox LBound(arrValue, 3)
End Sub

Result: 1, 1, 4, 12

UBOUND, also known as Upper Bound, is a function in VBA with its opposite function, LBOUND or Lower Bound function. This function defines the length of an array in a code. As the name suggests, UBOUND is used to define the upper limit of the array.

VBA UBOUND Function

How do you tell the maximum length of the array in Excel? Yes, we can manually see and update the maximum length of the array but if you are doing it all this while, then today is the end because we have a function called UBOUND to determine the maximum length of the array. Follow this article to learn more about the UBOUND function in Excel VBA.

UBOUND stands for Upper Bound. In coding, we may often require finding the maximum length of the array. For example, MyResult(24) means the array name MyResult holds 25 values because the array starts from zero, not from one. So, 24 means +1, i.e., a total of 25 values.

Here, the maximum length of the array is 24. Instead of supplying the array length manually, we can use the built-in function UBOUND to get the maximum length of the array.

The code is: UBOUND (MyResult), i.e., UBOUND (24)

So, the Excel VBA UBOUND function represents the upper bound of the array size.

Table of contents
  • VBA UBOUND Function
    • How to use the VBA UBound Function in Excel?
    • Examples of UBOUND Function in Excel VBA
      • Example #1
      • Example #2 – Using the Excel VBA UBOUND Function to Copy the Data
    • Things to Remember
    • Recommended Articles

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA UBOUND (wallstreetmojo.com)

How to use the VBA UBound Function in Excel?

The formula of VBA UBOUND is very simple because it has only two parameters to it.

UBound (Arrayname [,Dimension])
  • Array Name: This is the name of the array name we have defined. For example, in the above example, MyResult is the array name.
  • [Dimension]: If the array has more than one dimension, then we need to specify the dimension of the array. If you ignore it, it will treat the first dimension by default.

The Excel VBA UBOUND function is very useful in determining the length of the loops while running.

Examples of UBOUND Function in Excel VBA

Below are the practical examples of the VBA UBound function.

You can download this VBA UBound Function Template here – VBA UBound Function Template

Example #1

To start the proceedings, let me write the simple code. Then, follow the below steps to apply the VBA UBOUND function.

Step 1: Start the excel macroA macro in excel is a series of instructions in the form of code that helps automate manual tasks, thereby saving time. Excel executes those instructions in a step-by-step manner on the given data. For example, it can be used to automate repetitive tasks such as summation, cell formatting, information copying, etc. thereby rapidly replacing repetitious operations with a few clicks.
read more
and define the variable name.

Code:

Sub Ubound_Example1()
    Dim ArrayLength(0 To 4) As String

vba UBound Example 1

Step 2: We will assign values to this array name.

Code:

Sub Ubound_Example1()
  Dim ArrayLength(0 To 4) As String
  ArrayLength(0) = "Hi"
  ArrayLength(1) = "Friend"
  ArrayLength(2) = "Welcome"
  ArrayLength(3) = "to"
  ArrayLength(4) = "VBA Class"
End Sub

vba UBound Example 1-1

Step 3: Now, using a message box with the UBOUND function, we will see the maximum length of the array.

Code:

Sub Ubound_Example1()
  Dim ArrayLength(0 To 4) As String
  ArrayLength(0) = "Hi"
  ArrayLength(1) = "Friend"
  ArrayLength(2) = "Welcome"
  ArrayLength(3) = "to"
  ArrayLength(4) = "VBA Class"
  MsgBox "Upper Bound Length is: " & UBound(ArrayLength)
End Sub

vba UBound Example 1-2

Step 4: Run this code by pressing the F5 key, or you can also run the code manually, as shown in the below screenshot.

vba UBound Example 1-3

The message box will show you the upper bound number of the array.

vba UBound Example 1-4

Using the Excel VBA UBOUND function, we can get the upper bound length of an array.

Example #2 – Using the Excel VBA UBOUND Function to Copy the Data

Assume you have a list of data in one Excel sheet like the below one.

vba UBound Example 2

This data will update daily. Therefore, you must copy it to the new sheet every time it updates. Updating this manually will take considerable time in your workplace, but we will show you a simple macro code to automate this.

Step 1: Create a Macro and define the array variable.

Code:

Sub Ubound_Example2()
  Dim DataRange() As Variant
End Sub

vba UBound Example 2-1

Step 2: Now, activate the datasheet by refereeing to its name.

Code:

Sub Ubound_Example2()
    Dim DataRange() As Variant
    Sheets("Data Sheet").Activate
End Sub

vba UBound Example 2-2

Step 3: Now, assign the data range to the defined variable using the code below.

Code:

Sub Ubound_Example2()
    Dim DataRange() As Variant
    Sheets("Data Sheet").Activate
    DataRange = Range("A2", Range("A1").End(xlDown).End(xlToRight))
End Sub

vba UBound Example 2-3

Step 4: Now, add a new worksheet to the workbook.

Code:

Sub Ubound_Example2()
    Dim DataRange() As Variant
    Sheets("Data Sheet").Activate
    DataRange = Range("A2", Range("A1").End(xlDown).End(xlToRight))    
    Worksheets.Add
End Sub

Example 2-4

Step 5: Now, add the data to the newly added sheet using the Excel VBA UBOUND function in the form of the below code.

Code:

Sub Ubound_Example2()
    Dim DataRange() As Variant
    Sheets("Data Sheet").Activate
    DataRange = Range("A2", Range("A1").End(xlDown).End(xlToRight))     
    Worksheets.Add    
    Range(ActiveCell, ActiveCell.Offset(UBound(DataRange, 1) - 1, UBound(DataRange, 2) - 1)) = DataRange
End Sub

Example 2-5

The above code will offset the cells by the maximum length returned by the UBOUND function, and this range will equal the value of the array name “DataRange.

Step 6: Now, run this code. It will paste the value to the new sheet.

vba UBound Example 2-6

This code is dynamic because even when the data increases horizontally and vertically, it will automatically take the range. So, now we will add some dummy lines to the data.

Example 2-7

Now, we will once again run this code. It will now add the newly added lines as well.

vbaUBound Example 2-8

Code:

Sub Ubound_Example2()
    Dim DataRange() As Variant
    Sheets("Data Sheet").Activate
    DataRange = Range("A2", Range("A1").End(xlDown).End(xlToRight))   
    Worksheets.Add   
    Range(ActiveCell, ActiveCell.Offset(UBound(DataRange, 1) - 1, UBound(DataRange, 2) - 1)) = DataRange  
    Erase DataRange
End Sub

vbaUBound Example 2-9

Things to Remember

  • The UBOUND function returns the maximum length of the array.
  • The array starts from 0, not from 1.
  • If you want the lower value of the array, then you need to use VBA LBOUNDLBound in VBA or “Lower Bound” extracts the lowest number of an array. For example, if the array says “Dim ArrayCount (2 to 10) as String” then using LBound function we can find the least number of the array length i.e. 2.read more.
  • If the array has more than one dimension, you need to specify the dimension number.

Recommended Articles

This article is a guide to VBA UBound Function. Here, we learn how to use the VBA UBound function to find the Upper Bound Length in Excel, along with practical examples and downloadable templates. Below are some useful Excel articles related to VBA: –

  • VBA Class
  • VBA Variant Data Type
  • Arrays Function in VBA
  • VBA StrConv
  • VBA Rename Sheet

Понравилась статья? Поделить с друзьями:
  • Vba excel массивы range
  • Vba excel макрос изменения макроса
  • Vba excel массив чисел
  • Vba excel макрос для удаления макросов
  • Vba excel массив уникальных значений