0

Can any one kindly check the code, I explained the code in comments.

I am getting run error 13

My concern in the assign method that I am using. I want to assign the cell value in the array starting form position 0

Thank you very mush

Sub zones()

Dim Top10zones(0 To 9) As Long
Dim found As Boolean

Top10zones(0) = 309101502

NumRows = Range("A1", Range("A1").End(xlDown)).Rows.count

Dim Arry As Variant

Dim count As Integer
count = 0

' find the 10zones in row 1.
Range("A1").Select
    Do Until IsEmpty(ActiveCell)
         If ActiveCell.Value = Top10zones(0) Then
            found = True
            Exit Do
         End If

         ActiveCell.Offset(0, 1).Select
      Loop
   ' if found move to row 2 in the same cloumn.
      If found = True Then
      ActiveCell.Offset(1, 0).Select

      For j = 2 To NumRows
      If ActiveCell.Value <= 1 Then
         ' if the value <= 1 assign cells(j,1) to the array.
        Arry(count) = Cells(j, 1).Value
        count = count + 1
      End If
      ActiveCell.Offset(1, 0).Select

      ' repeat the process.
      Next j


      End If

End Sub
BigBen
  • 46,229
  • 7
  • 24
  • 40

1 Answers1

1

In VBA, arrays are initialized with a fixed length. For instance, an array of length 1 will only have a Array(0) index and none others. If you want to increase the size of the array (without destroying the current contents of the array), you need to use ReDim Preserve Arry(new_length). So if you ReDim Preserve Arry(10) your array is now ready for 10 elements, and if you had any elements already in the array they are preserved.

There are two ways to initialize an array.

1)

Dim myArry(0 to 1) as String

This is an array with two empty elements ready to accept a string.

2)

Dim myArry as Variant
myArry = Array("", "")

This is an array with two "empty" element ready to accept a string.

To change the length:

For i = 1 to 10
    ReDim Preserve myArry(i)
    myArry(i) = 'whatever
Next i
jclasley
  • 668
  • 5
  • 14
  • 1
    @sjr good point about 1, it was early in the morning for me. To your second point, I just wanted to illustrate that it's an empty Variant that then becomes an array. – jclasley Jan 27 '20 at 15:18