PDA

View Full Version : Ways of declaring arrays



theta
07-30-2012, 09:24 AM
I have seen a few ways of declaring arrays, can somebody please highlight the significance/differences of the methods :

Dim varMyArray() as Variant
Dim varMyArray() as Variant()

Dim arrMyArray() as String
Dim arrMyArray() as String()

Which is the correct naming convention? What is the significance of the extra () on the definition type.

Also, how would I populate a quick array...

arrMyArray = Array("Jan","Feb","Mar") ?

Bob Phillips
07-30-2012, 12:48 PM
The second and fourth are wrong and throw errors.

The first allows elements of any data type, the third only allows strings.

That way works fine, but you can also use

Dim arrMyArray() As Variant

arrMyArray = [{"Jan","Feb","Mar"}]

theta
07-31-2012, 03:20 AM
When I declare it as string I get a type mismatch? When I declare it as a variant it works?

Public arrrSheetsHiddenRows() as String

Sub UnhideRows()

arrSheetsHiddenRows = Array("Sheet1", "Sheet2", "Sheet3")

For i = 1 to UBound(arrSheetsHiddenRows)
Worksheets(arrSheetsHiddenRows(i)).Rows.EntireRow.Hidden = False
Next i

End sub

Bob Phillips
07-31-2012, 03:46 AM
When you try to load an array variable in one action from an array or a range it needs to be type variant, if you load it one by one, it can be type string.

Personally I never bother with anything other than variants for array variables.