{"id":16726,"date":"2023-11-06T18:05:57","date_gmt":"2023-11-06T18:05:57","guid":{"rendered":"https:\/\/officetuts.net\/excel\/?p=16726"},"modified":"2024-02-19T15:00:01","modified_gmt":"2024-02-19T15:00:01","slug":"get-the-length-of-an-array-in-vba","status":"publish","type":"post","link":"https:\/\/officetuts.net\/excel\/vba\/get-the-length-of-an-array-in-vba\/","title":{"rendered":"How to Get the Length of an Array in VBA"},"content":{"rendered":"\n
The VBA programming language provides a variety of tools for automating tasks in Excel and other Office products. One such tool is the array, a data structure that can hold multiple values. This tutorial will show you how to get the length of an array in VBA. This technique is useful when you need to loop through all the elements of an array or perform some computation based on the number of elements in the array.<\/p>\n\n\n\n
Before we get the length of an array, let’s first declare one. VBA uses the Dim<\/strong> keyword to declare an array. The size of the array is provided in parentheses. Here’s an example of how to declare an array with 5 elements in VBA:<\/p>\n\n\n\n Next, let’s assign some values to our array. This can be done using the array index, which starts from zero:<\/p>\n\n\n\n To get the length of the array, we will use the UBound<\/strong> function in VBA. ‘UBound’ stands for ‘Upper Bound’, and it returns the highest index in the array. To get the size, you add 1 to the result (because the array index starts at zero). Here’s the code:<\/p>\n\n\n\n Now variable ‘length’ holds the number of elements in the array.<\/p>\n\n\n\n Here’s the full VBA code showing how to declare an array, assign values, and then get the array’s length:<\/p>\n\n\n\nDim arr(5) As Integer<\/code><\/pre>\n\n\n\n
Step 2: Assign Values to the Array<\/h3>\n\n\n\n
arr(0) = 1\narr(1) = 2\narr(2) = 3\narr(3) = 4\narr(4) = 5<\/code><\/pre>\n\n\n\n
Step 3: Get the Length of the Array<\/h3>\n\n\n\n
Dim length As Integer\nlength = UBound(arr) + 1<\/code><\/pre>\n\n\n\n
Full Code<\/h2>\n\n\n\n
Sub GetLength()\r\n Dim arr(5) As Integer\r\n arr(0) = 1\r\n arr(1) = 2\r\n arr(2) = 3\r\n arr(3) = 4\r\n arr(4) = 5\r\n \r\n Dim length As Integer\r\n length = UBound(arr) + 1\r\n MsgBox length\r\nEnd Sub\r<\/code><\/pre>\n\n\n\n