Hi,
I am having problems with a UDF I found. This sums values across different sheets (the ones you pick) in the workbook. The problem I am having is that when I do a full calc the function works but if i open a new workbook or worksheet I get a #ref error. I need to reference this in another worksheet and am unable to. I am a beginner in VBA and have no idea why this isn't working. Thanks for any help in advance.
I am having problems with a UDF I found. This sums values across different sheets (the ones you pick) in the workbook. The problem I am having is that when I do a full calc the function works but if i open a new workbook or worksheet I get a #ref error. I need to reference this in another worksheet and am unable to. I am a beginner in VBA and have no idea why this isn't working. Thanks for any help in advance.
Code:
Public Function SumOfSheets(RangeAddress As String, _ ParamArray SheetNames() As Variant) As Variant
Dim Total As Double
Dim N As Long
Dim R As Range
Dim WS As Worksheet
Dim FirstWS As Long
Dim LastWS As Long
On Error Resume Next
' ensure SheetNames is present
If IsError(LBound(SheetNames)) Then
SumOfSheets = CVErr(xlErrValue)
Exit Function
End If
' ensure RangeAddress is included
If RangeAddress = vbNullString Then
SumOfSheets = CVErr(xlErrValue)
Exit Function
End If
' ensure RangeAddress is a valid range
Set R = Worksheets(1).Range(RangeAddress)
If Err.Number <> 0 Then
SumOfSheets = CVErr(xlErrRef)
Exit Function
End If
If SheetNames(0) = ":" Then
' working with range of sheets. ensure we
' have both start and end sheets
If IsError(SheetNames(1)) Or _
IsError(SheetNames(2)) Then
SumOfSheets = CVErr(xlErrRef)
End If
' get the first sheet index
FirstWS = Worksheets(SheetNames(1)).Index
If Err.Number <> 0 Then
SumOfSheets = CVErr(xlErrRef)
Exit Function
End If
' get the last sheet index
LastWS = Worksheets(SheetNames(2)).Index
If Err.Number <> 0 Then
SumOfSheets = CVErr(xlErrRef)
Exit Function
End If
' ensure first sheet is <= last sheet
If FirstWS > LastWS Then
SumOfSheets = CVErr(xlErrRef)
Exit Function
End If
'loop and sum
For N = FirstWS To LastWS
Set R = Worksheets(N).Range(RangeAddress)
If Err.Number <> 0 Then
SumOfSheets = CVErr(xlErrRef)
Exit Function
End If
Total = Total + Application.Sum(R)
Next N
' return the result
SumOfSheets = Total
Exit Function
Else
' we have a list of sheets. loop and sum.
For N = LBound(SheetNames) To UBound(SheetNames)
Total = Total + Application.Sum( _
Worksheets(SheetNames(N)).Range(RangeAddress))
If Err.Number <> 0 Then
SumOfSheets = CVErr(xlErrRef)
Exit Function
End If
Next N
' return the result
SumOfSheets = Total
End If
End Function