Redim statement - Why?

pedie

Well-known Member
Joined
Apr 28, 2010
Messages
3,875
Hi, several times i have seen this word "redim something(6) as string" often...
What does it mean and when we as need to use it?

Thanks:)
 

Excel Facts

Return population for a City
If you have a list of cities in A2:A100, use Data, Geography. Then =A2.Population and copy down.
Press F1 with the cursor in or near the word Redim to get help in the VBE.

It is used for arrays to redimesion them. Redim Preserve is often used to both redimension the array and preserve existing content.
 
Upvote 0
Hi, pedie.
Redim is usually used for resizing an array.

For example, if you had a array declared in the beginning of a Sub or w/e.

Error:
Code:
Sub Test()
Dim strData() As String
strData(2) = "Hi"
MsgBox strData(2)
End Sub
and you want to store a value in index:=2 with Option Explicit on.
You will be unable to assign value to it because it doesn't have a specified range array.

However, when you do have a fixed array
Fixed:
Code:
Sub Test2()
    Dim strData(0 To 5) As String
    strData(2) = "Hi"
    MsgBox strData(2)
End Sub

Altho you will be able to declare it and assign values to it, you will be unable to append more data at the end of your array without declaring a new array.

So, a method came up and it was the ReDim statement.
ReDim allows you to resize the array or newly declare an existing variable.

Code:
Sub Test3()
    Dim strData$()
    ReDim strData$(0 To 6)
    strData(6) = "Hi"
End Sub

Moreover, there is one more option about ReDim you will need to learn and that's Preserve.

Because ReDimming does not store previous values stored, you will need to use Preserve if you want the original values still stored in their own places.
Code:
ReDim Preserve strData$(0 To 6)

Hope it helps.
 
Upvote 0

Forum statistics

Threads
1,224,596
Messages
6,179,807
Members
452,944
Latest member
2558216095

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top