Что такое ubound vba excel

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]

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 UBound

Excel VBA UBound Function

How often do you come up with a situation where you need to mention the maximum length or upper bound of an array data working with Excel? Most of the times, right? And how do you find the same? Maybe manually most of the time. However, you can automate it and get the maximum length or upper bound of an array using a VBA function called UBound.

Moreover, it has the most beautiful way to looping through. Like, if you are using a For loop in your array, you definitely wanted to loop all the elements of the array. In that case, it would be a tedious job to find out upper bound manually and mention it in the loop. It will also reduce the generality of the code. Therefore, VBA UBound function comes handy in such scenarios.

UBound stands for upper bound and it gives upper bound or maximum length of the array in Excel VBA.

Formula For UBound Function in Excel VBA

Excel VBA UBound function has the following syntax.

UBound (Arrayname [, Dimension])

Where,

  • Arrayname: Name of the array you have defined. This argument is a mandatory/required argument.
  • Dimension: Optional argument which specifies the dimension of an array. Whether it’s a one-dimensional, two-dimensional or multi-dimensional array. By default, it will assume the one-dimensional array if not specified.

As this function has only two arguments, it becomes much easier to remember the syntax of this function.

How to Use Excel VBA UBound Function?

We will learn how to use a VBA UBound function with few examples in Excel.

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

Example #1 – VBA UBound with One-Dimensional Array

Follow the below steps to use UBound function in VBA.

Step 1: In the Developer Tab click on Visual Basic to open the VB Editor.

VBA UBOUND Example 1-1

Step 2: Click on Insert and select the Module tab to add a new blank module to VBE.

VBA UBOUND Example 1-2

Step 3: In the VBE, start writing the macro and define the variable name.

Code:

Sub Onedm_Ubound()

Dim IndiaCity(4) As String

End Sub

VBA UBOUND Example 1-3

Here variable IndiaCity is defined with 5 elements. The variable type is a string.

Note: Array starts from 0 (Zero). Hence, this array will consist of 5 elements.

Step 4: Assign values to the array elements.

Code:

Sub Onedm_Ubound()

Dim IndiaCity(4) As String

IndiaCity(0) = "Mumbai"
IndiaCity(1) = "Bengaluru"
IndiaCity(2) = "Hyderabad"
IndiaCity(3) = "Delhi"
IndiaCity(4) = "Pune"

End Sub

VBA UBOUND Example 1-4

Here, the zeroth element has a value assigned as “Mumbai”, the First element has a value assigned as “Bengaluru” and so on.

Step 5: Use the UBound function along with MsgBox to get the upper bound for the array.

Code:

Sub Onedm_Ubound()

Dim IndiaCity(4) As String

IndiaCity(0) = "Mumbai"
IndiaCity(1) = "Bengaluru"
IndiaCity(2) = "Hyderabad"
IndiaCity(3) = "Delhi"
IndiaCity(4) = "Pune"

MsgBox "Upper Bound for the Array is: " & UBound(IndiaCity)

End Sub

VBA UBOUND Example 1-5

Step 6: Run this code by hitting F5 directly or manually hitting the Run button on the upper left panel. A message box will pop up with the message “Upper Bound for the Array is: 4”.

Result of Example 1-6

Please note that UBound function does not find out the upper limit from the elements of Array. It just finds out the maximum number of elements the array holds.

Example #2 – VBA UBound with Two-Dimensional Array

Follow the below steps to use UBound function in VBA.

Step 1: Define a variable which can hold two-dimensional data.

Code:

Sub TwoDm_UBound()

Dim Array_Test(0 To 6, 1 To 8) As String

End Sub

VBA UBOUND Example 2-1

Step 2: Define a new variable Message and use it under MsgBox. This variable will help us printing the upper bounds of both dimensions simultaneously.

Code:

Sub TwoDm_UBound()

Dim Array_Test(0 To 6, 1 To 8) As String
Dim Message
MsgBox Message

End Sub

VBA UBOUND Example 2-2

Step 3: Now, try the following statements which allow the system to print both dimensions of the array under the same message box.

Code:

Sub TwoDm_UBound()

Dim Array_Test(0 To 6, 1 To 8) As String
Dim Message
Message = "Upper bound for first dimension is: " & UBound(Array_Test, 1) & vbCrLf
Message = Message & "Upper bound for second dimension is: " & UBound(Array_Test, 2) & vbCrLf
MsgBox Message

End Sub

VBA UBOUND Example 2-3

The two statements mentioned in the above code allow the system to print both dimensions in the same message box. The first statement stores the value of the upper bound for the first dimension in variable Message and ends the line (vbCrLf). The second statement adds the first value assigned to variable Message and combines it with the upper bound of second dimensions with a pop-up message.

As the vbCrLf is used in both statements, it works as newline/carriage return here in both statements.

Step 4: Run the code by hitting F5 or Run button and see the output.

Result of Example 2-4

On similar lines, we can go until multiple dimensions and see the upper bound for each of them.

Example #3 – UBound Function to Update the Data in Sheet Automatically

Suppose you have a data set as shown in below screenshot.

Example 3-1

This data gets updated and you need to copy the updated data every now and then. Now, it’s really a tedious job to always check for the data updates and then copy it to the new sheet. It consumes a lot of time as well. Can we try automating it using UBound function in VBA? Let’s see.

Follow the below steps to update the data in sheet automatically using VBA UBound function:

Step 1: Define a variable by creating a macro.

Code:

Sub Ex3_UBound()

Dim DataUpdate() As Variant

End Sub

VBA UBOUND Example 3-2

Step 2: Activate the worksheet which contains your data. In this case, the sheet name is “Data”.

Code:

Sub Ex3_UBound()

Dim DataUpdate() As Variant
Sheets("Data").Activate

End Sub

VBA UBOUND Example 3-3

Step 3: Assign the range to the variable we just created. We will use activated sheets range for this purpose.

Code:

Sub Ex3_UBound()

Dim DataUpdate() As Variant
Sheets("Data").Activate
DataUpdate = Range("A2", Range("A1").End(xlDown).End(xlToRight))

End Sub

VBA UBOUND Example 3-4

Step 4: Add a new worksheet to your Excel, where the updated data can be copied and pasted.

Code:

Sub Ex3_UBound()

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

End Sub

VBA UBOUND Example 3-5

Step 5: Now, use the below code line that allows the data from the “Data” sheet to be copied and pasted in a newly created excel sheet automatically.

Code:

Sub Ex3_UBound()

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

End Sub

VBA UBOUND Example 3-6

The above code will offset the cells from “Data” sheet up-to upper bound which can be obtained by UBound function used and assigns the range to the variable DataUpdate.

Step 6: Run the code by hitting F5 or Run button and see the output.

Result of Example 3-7

As you can see, there is a new sheet added in the Excel Workbook where all the data from the “Data” sheet gets copied automatically.

This is a dynamic code. What I mean saying it dynamic is, though I add column-wise and row-wise, it will automatically be copied to a new sheet.

Step 7: Let’s add some rows and columns to the data and see if it actually works.

Example 3-8

Step 8: Hit the Run button again after the data-sheet is updated and see the magic.

Result of Example 3-9

If you can see, a new sheet is added (colored) and a new column of Age along with two new rows is added as well in that sheet. It means, whatever we update in the master file (Data), this code will automatically copy everything from that and paste it in a new sheet.

Things to Remember

  • UBound gives the upper bound/maximum length of an array and not the upper bound from the data points present in an array.
  • The array always starts from the 0th position as parallel to most programming languages like C, C++, Python.
  • If your array is multidimensional, you have to specify the dimension argument as well which takes numeric whole values like 1, 2, 3, etc. 1 stands for One-Dimension, 2 for Two-Dimensional and so on.

Recommended Articles

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

  1. VBA Split
  2. VBA Match
  3. VBA RGB
  4. VBA Worksheets

Массивы в 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)


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

Понравилась статья? Поделить с друзьями:
  • Что такое two word verbs
  • Что такое trigger word
  • Что такое translate the word combinations
  • Что такое track changes в word
  • Что такое tools в word