Hi,
I'm new to VBA (although I know Matlab well), and I'm having trouble working with arrays and ranges. In VBA, the application.worksheetfunction matrix algebra functions all seem to work with arrays and ranges. I'd like some of the custom matrix algebra functions I write to do the same, but I can't figure out what to do.
For example, suppose I write a function which doubles every element in a range. I know that it's a dumb function, but it'll show where I'm getting confused.
This function works fine when I use it on a range in a spreadsheet.
But now suppose I'm writing a sub, and I want to call the DoubleMatrix function.
This sub doesn't work, because inputMatrix isn't a range. I'm not sure what to do here. Do I dim inputMatrix as a range, and populate it with a loop? I tried this, but I couldn't get it to work. Should I change the DoubleMatrix function to work with both ranges and arrays? In this case, I'd have to determine whether the input is an array or a range, and figure out the dimensions of the input using, respectively, Ubound() or count. This seems kind of clunky. I'm really lost, so I'd appreciate any help.
I'm new to VBA (although I know Matlab well), and I'm having trouble working with arrays and ranges. In VBA, the application.worksheetfunction matrix algebra functions all seem to work with arrays and ranges. I'd like some of the custom matrix algebra functions I write to do the same, but I can't figure out what to do.
For example, suppose I write a function which doubles every element in a range. I know that it's a dumb function, but it'll show where I'm getting confused.
Code:
Function DoubleMatrix(inMatrix1 As Range)
RowCount = inMatrix1.Rows.Count
ColCount = inMatrix1.Columns.Count
Dim tempMatrix() As Double
ReDim tempMatrix(1 To RowCount, 1 To ColCount)
For i = 1 To RowCount
For j = 1 To ColCount
tempMatrix(i, j) = 2 * inMatrix1(i, j)
Next j
Next i
DoubleMatrix = tempMatrix
End Function
This function works fine when I use it on a range in a spreadsheet.
But now suppose I'm writing a sub, and I want to call the DoubleMatrix function.
Code:
Sub TryingToCallFunction()
Dim inputMatrix(1 To 4, 1 To 4) as double
For i = 1 To 4
For j = 1 To 4
inputMatrix(i, j) = i + j
Next j
Next i
test = DoubleMatrix(inputMatrix)
End Sub
This sub doesn't work, because inputMatrix isn't a range. I'm not sure what to do here. Do I dim inputMatrix as a range, and populate it with a loop? I tried this, but I couldn't get it to work. Should I change the DoubleMatrix function to work with both ranges and arrays? In this case, I'd have to determine whether the input is an array or a range, and figure out the dimensions of the input using, respectively, Ubound() or count. This seems kind of clunky. I'm really lost, so I'd appreciate any help.