Reputation: 49
I'm trying to write a function that takes as input a square matrix that should have in its cells
on and above the diagonal (from bottom left to right top) positive numbers, and
below the diagonal empty cells,
likes this 3 x 3 matrix (first cell contains # 10, second cell # 5, etc.):
10 5 1
9 6
4
Before I do anything with this matrix, I need to verify that the cells on and above the diagonal contain positive numbers and that the other cells are empty. I wrote the code below.
The problem is that it gives me an overflow error at the second For loop, and for the life of me, I don't understand why. With a 3 x 3 matrix (that is, n = 3, p = 3), the first line of the second For loop would be: For i = 3 to 2 Step -1. What is the problem here?
Option Base 1
Private Sub triangle1()
Dim y As Variant
y = Application.InputBox( _
Prompt:=" Choose a square matrix in a worksheet : ", Type:=8)
Dim i As Byte, j As Byte, n As Byte, p As Byte, s As Byte
n = UBound(y, 1)
p = UBound(y, 2)
Debug.Print LBound(y, 1), n, p
s = 1
If n <> p Then
Debug.Print "False"
Exit Sub
Else
' First For loop
For i = 1 To n
For j = 1 To p
If y(i, j) <= 0 Or Not IsNumeric(y(i, j)) Then
Debug.Print "False"
Exit Sub
End If
Next
p = p - 1
Next
' Second For loop
For i = n To 2 Step -1
s = s + 1
For j = s To p
If Not IsEmpty(y(i, j)) Then
Debug.Print "False"
Exit Sub
End If
Next
Next
Debug.Print "True"
End If
End Sub
Upvotes: 1
Views: 2237
Reputation: 40224
The problem is with the byte
types. If you replace them with Integer
or Long
it should run.
The reason is that byte
cannot handle negative numbers (only integers 0-255), so it doesn't know what to do with the Step -1
since the step is the same type as the iterator.
Upvotes: 4