简体   繁体   中英

In Excel VBA, How do I change the cell range that was passed as a user input to a function

I havw two columns of data which I called XVals and YVals from A1:A65 and B1:B65 respectively. I want to find 20% of the maximum value in YVals for which I use the min function and then after interpolation find the corresponding Xvals value.

The problem is that because YVals is a traingular function there will be two such 20% corresponding XVals values. I just want to select one and so I thought the best way would be to redefine the range from A1:A65 to "A"&MatchVal&":A65" where MatchVal = WorksheetFunction.Match(WorksheetFunction.Max(YVals), YVals, 1) . But using plain ampersand characters I am not able to manipulate the range addresses.

Please suggest me a way to change this range from A1:A65 to say A50:A65 if MatchVal is 50. After this manipulation I can interpolate and get my value for XVals which lies on the downward slope.

Declare a variable of range type and use Set . Something like:

Dim rng As Range '~~> this will hold your new range

On Error Resume Next
MatchVal = WorksheetFunction.Match(WorksheetFunction.Max(YVals), YVals, 1)
If Err.Number <> 0 Then MsgBox "No match found.": Exit Sub
On Error Goto 0

Set rng = Range("A" & MatchVal & ":A65")

Take note of the OERN and OEG0 lines.
I added that to make sure that your code does not error out when no match is found.
Although, you mentioned there will always be 2 matches, it pays to have possible errors checked.
You can remove it otherwise it you think it is already overkill. HTH.

 =INDIRECT("A"&MatchVal&":A65")

INDIRECT()函数使您可以输入文本或提供文本的动态值,并将它们评估为单元格ID。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM