Excel UDF to sum ranges on variable worksheets

时间:2016-08-31 18:37:31

标签: excel-vba udf vba excel

This is my first post here, so I will do my best to be as clear as possible.

I have sort of settled on a UDF as being the correct solution here, but that is mostly because I couldnt figure out what built in function would work.

My workbook starts out having two sheets: "Summary Sheet" and "{System Template}". On Summary Sheet, I create a list of systems, and from that list I have some code that generates new worksheets using {System Template} and names the sheets based on the values in the list, which is working just fine. In the cell next to the one that contains the system name on the summary sheet, I am trying to sum the values in the range "Q:Q" for each of the different systems on their respective sheet. The only part of the range that is changing is the sheet name where the data is coming from. This is where I am having trouble. I get a #Value error and I have no idea how to figure out where the problem is. Normally I would use the built in formula evaluation tool, but it is kind of useless with a UDF. Any help would be much appreciated.

Function FrictionSum(rngInput As Range)
    Dim rngCell, rngDomain As Range
    Dim strName As String
    FrictionSum = 0

    'FrictionSum = rngInput.Value
    Set rngDomain = Sheets(strName).Range("Q:Q")

        For Each rngCell In rngDomain
            FrictionSum = FrictionSum + rngCell.Value
        Next rngCell

End Function

1 个答案:

答案 0 :(得分:0)

As stated the formula:

=SUM(INDIRECT("'" & A1 & "'!Q:Q"))

Should do what you want.

The worksheet Function Sum will do what you want without the need to iterate. Also make sure you assign the value to strName.

code:

Function FrictionSum(rngInput As Range) As Double
    Dim rngDomain As Range
    Dim strName As String


    strName = rngInput.Value


    Set rngDomain = Sheets(strName).Range("Q:Q")
    FrictionSum = Application.WorksheetFunction.Sum(rngDomain)


End Function