1

I have input array {{1,4}, {1,3}, {1,4,7}}

Dim array1() As Long
ReDim array1(3, 3)
array1(1, 1) = 1
array1(1, 2) = 4
array1(2, 1) = 1
array1(2, 2) = 3
array1(3, 1) = 1
array1(3, 2) = 4
array1(3, 3) = 7

I would like to have output array (which is length of each subarray) {2,2,3} I am thinking to use for loop as following

Dim i As Long
i = UBound(array1, 1)

Dim outputarray() As Long
ReDim outputarray(i) As Long
For j = 1 To i
    outputarray(i) = UBound(array1(i), 2)   'ERROR APPEAR
Next j

i added Option Base 1

2
  • Great! What's the question? Commented Nov 6, 2014 at 4:14
  • i would like to generate a output array {2,2,3} for above case. and i want a general case.
    – useR
    Commented Nov 6, 2014 at 5:54

2 Answers 2

4

The length of each subarray stay the same, its always 3 in your case. Your redim has defined the number you want to get. So there's no point trying to retrieve it like you want to do.

The fact that you don't move any values in

array1(1, 3)
array1(2, 3)

doesn't affect the dimensions of your array. You'll find values in these what-you-think-empty array's cells, and it will be 0 because you declared your array as long. If you had declared it as string, you would find a blank string in them, neither null nor "nothing".

You have input array {{1,4,0}, {1,3,0}, {1,4,7}}

If your aim is to find which elements of your array are 0 because you didn't moved anything in them, that's another story not related to the length of your array.

2

I agree with Thomas' answer above.

If you do find yourself interested in knowing the number of populated array values in the array, you might consider the following:

  • Start with the first row, and the right-most value in that array. So your for loop would actually be two loops - one to go through the first dimension, and one to go through the second dimension.
  • Move left through the array until you run into a non-zero value. Keep a count of the total values that are zero. When you run into a non-zero value, subtract the total zero values from the second dimension of the array. This will give you the "length" that you were looking for before.

So for example:

Dim i As int
Dim j As int
Dim h As int
Dim w As int
h = UBound(array1, 1)
w = UBound(array1, 2)
Dim rowVals as int
Dim arrVals as int

For i = 0 To h
    rowVals = 0
    For j = w to 0 Step -1

        if array1(i,j) = 0 Then
            exit for
        else
            rowVals = rowVals + 1
        end if
    Next
    arrVals = arrVals + rowVals
Next

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.