VBA Programming Series...29 - IT Skills

This blog is for IT lovers, accounts and finance executives who want to add value in their professional life.

test

Welcome to our blog. This blog is for IT lovers, Accounts/Finance Executives who wants to add value in their career path.

Search This Blog

Friday, 8 June 2018

VBA Programming Series...29

test

Dynamic arrays


You can also create dynamic arrays. A dynamic array doesn’t have a preset number of elements. Declare a dynamic array with an empty set of parentheses:


Dim MyArray () As Integer

Before you can use this array, you must use the ReDim statement to tell VBA how many elements the array has. Usually, the number of elements in the array is determined while your code is running. You can use the ReDim state-ment any number of times, changing the array’s size as often as needed. The following example demonstrates how to change the number of elements in a
dynamic array. It assumes that the NumElements variable contains a value, which your code calculated.


ReDim MyArray (1 To NumElements)

When you redimension an array by using ReDim, you wipe out any values cur-rently stored in the array elements. You can avoid destroying the old values by using the Preserve keyword. The following example shows how you can preserve an array’s values when you redimension the array:


ReDim Preserve MyArray(1 To NumElements)

If MyArray currently has ten elements and you execute the preceding state-ment with NumElements equaling 12, the first ten elements remain intact, and the array has room for two additional elements (up to the number contained in the variable NumElements). If NumElements equals 7 however, the first seven elements are retained but the remaining three elements meet their demise.




No comments:

Post a Comment

Popular

Welcome to our blog. If you want to; learn writing skills, preparation for CSS/Corporate laws, IT skills, downloading Business/IT books, and many more; this blog is for you.