Reputation: 11
I'm working on this project and I need to create a function in VBA in order to store a formula and return the result in excel using the index function. My code is as below and i created just a simple dummy function for testing purposes. In excel I believe the function should be =INDEX(NewArray,,1)? Any help on this would be greatly appreciated Thanks
Public Function NewArray(a As Integer, b As Integer) As Long()
Dim arr() As Long
ReDim arr(1 To 10, 1 To 5) As Long
Dim row As Integer
Dim col As Integer
For row = 1 To 5
arr(row, 1) = (row + 1)
Next row
NewArray = arr(a, b)
End Function
Upvotes: 1
Views: 120
Reputation: 54757
Option Explicit
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose: Creates a 2D one-based array with 'a' rows and 'b' columns.
' populated by the product of rows and columns.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function NewArray(ByVal a As Long, ByVal b As Long) As Long()
Dim arr() As Long: ReDim arr(1 To a, 1 To b)
Dim r As Long
Dim c As Long
For r = 1 To a ' loop (iterate) through rows
For c = 1 To b ' loop (iterate) through columns
arr(r, c) = r * c ' e.g. product of the current row and column
Next c
Next r
NewArray = arr ' don't forget to return the result
End Function
5 rows, 7 columns
Sub NewArrayTEST()
Dim arr() As Long: arr = NewArray(5, 7)
Dim r As Long
Dim c As Long
For r = 1 To UBound(arr, 1)
For c = 1 To UBound(arr, 2)
Debug.Print r, c, arr(r, c)
Next c
Next r
End Sub
In Excel, you can return the element at the intersection of the 2nd row and the 3rd column using the INDEX function:
=INDEX(NewArray(5,7),2,3)
The result is 6
since we added the product 2*3
.
Upvotes: 1