简体   繁体   中英

VBA Passing a Range Name from a Different Worksheet to a Function

Maybe I'm trying to do too much here, but I've worked for hours on this with no luck. I hope you can help.

I am creating a function whose only parameter is a named range on a another sheet in the same workbook. My problem is that I can't figure out how to pass that name into the function and use it.

My goal is call the function to sum the column specified by the named range on the other worksheet, called Client Payments.

Here's my code that works:

Function PayPerMonth()
PayPerMonth = Application.WorksheetFunction.Sum(Worksheets("Client Payments").Range("C:C"))
End Function

I get a total that is correct, but of course I specified the column in the function. Not too useful.

Here's what I tried that doesn't work:

Function PayPerMonth(ColumnToAdd)
PayPerMonth = Application.WorksheetFunction.Sum(Worksheets("Client Payments").Range("ColumnToAdd"))
End Function

It doesn't work when I remove the quotes around ColumnToAdd, and many other variations I have tried.

What I want to do is to enter =PayPerMonth(MBPADV) or =PayPerMonth(SBTSADV) etc. to call the function and aim at the right column, where MBPADV and SBTSADV are named columns.

I'm not hung up on using the column names. It just makes it more readable (to me, anyway!).

Can this be done?

Range("named range") returns a range in the WorkBook so it should be good to pass into your function that takes a range.

Assuming you have a named range in the workbook called ColumnToAdd , this should work:

Function PayPerMonth(ColumnToAdd)
  PayPerMonth = Application.WorksheetFunction.Sum(Range("ColumnToAdd")
End Function

Update per comments :

Function PayPerMonth(ColumnToAdd As Range)
  PayPerMonth = Application.WorksheetFunction.Sum(Range(ColumnToAdd))
End Function

Usage:

Dim MyRange as Range
MyRange = Sheet.Columns("C")
Amount = PayPerMonth(MyRange)

Note:

Your function call will return a variant. You may want to declare As Integer , As Single or As Float at the end of Function PayPerMonth(ColumnToAdd As Range) to help A) speed the processing, since Excel won't have to spend time trying to figure out what type of variable it's working with, and B) yourself/the next coder when it comes time to maintain the code - being explicit makes your code more readable.

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