I have a table in Excel which looks like this:
A C D
0 0.00% 0.00% 0.00%
473 0.00% 0.00% 3.40%
641 13.80% 13.80% 10.40%
646 13.80% 13.80% 10.40%
3337 13.80% 13.80% 13.80%
3454 13.80% 13.80% 13.80%
The function is of the form myFunction(x,y,thresholds_table) where x can be A, C or D and thresholds_table is the whole table. The function involves looking up values from one of the three columns depending on the value of x. If I manually specify a column (eg set r=2), the function works fine, but I can't work out how to choose the column.
I'm new to VBA and used to programming languages with much better support for array slicing, so perhaps I'm going about this the wrong way. The code I'm trying to use is:
Dim rates As Range
rates = Application.WorksheetFunction.Index(thresholds_table, 1, 0)
r = Application.WorksheetFunction.Match(x, rates)
using the INDEX function to select the top row, then Match to find the column index. However, it always returns a VALUE error.
This seems like it must be simple, but I've done a lot of googling and not been able to find an answer!
EDIT:
Sorry, I wasn't entirely clear: the "y" argument isn't used in this part of the function. Basically I just need a function which returns 2 if x=A, 3 if x=C or 4 if x=D. I don't want to put it in directly like that though since the A/C/D may change in the future, so it needs to use whatever the column headings are.
Perhaps a little long winded, but does this explain things a little better?
Public Function myFunction(x, y, thresholds_table As Range) As Variant
Dim rates As Variant
With Application
rates = .Index(thresholds_table, 1, 0)
myFunction = .Match(x, rates)
End With
End Function
The functions return an array, rather than a range object.
This could be shortened, but I think you'd get far better performance from simply using a formula in the sheet
Your declaration of rates is incorrect - the function returns a 2 dimensional array
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.