0
votes

I can't figure out why I keep getting an object error in VBA when calling a function with a desired range/variable. I want to call the SumSameCells function from a sub with the B8, B9, B10 as desired/destination cells (rng As Range)

Any help would be greatly appreciated. Thanks

Sub MySums()

Call SumSameCells(B8)
Call SumSameCells(B9)
Call SumSameCells(B10)

End Sub

Function SumSameCells(rng As Range)

    x = 0
    For i = 2 To 3
        x = x + Sheets(i).Range(" & rng.Address & ")
    Next i
    Sheet1.Range(" & rng.Address & ") = x

End Function
2

2 Answers

0
votes

This:

Call SumSameCells(B8)

isn't passing the Range B8 but an undeclared variable named B8

Using Option Explicit would warn you about this type of error.

This would be simpler:

Sub MySums()

SumSameCells "B8"
SumSameCells "B9"
SumSameCells "B10"

End Sub

Function SumSameCells(addr As String)

    x = 0
    For i = 2 To 3
        x = x + Sheets(i).Range(addr).Value
    Next i
    Sheet1.Range(addr) = x

End Function
0
votes

Variation on the already given answer.

  1. Functions return something. You are using a return value so make it a sub.
  2. No need for a loop in this case. You can just sum direct.
  3. Declare the appropriate type for x. Option Explicit has already been mentioned.
  4. Use the worksheets collection to avoid trying to work with a chart sheet.
  5. Drop the call keyword as is obsolete.

Code:

Option Explicit
Public Sub MySums()
    SumSameCells "B8"
    SumSameCells "B9"
    SumSameCells "B10"
End Sub

Public Sub SumSameCells(ByVal addr As String)
  Dim x As Double '<== Use whatever appropriate type is
  x = Application.WorksheetFunction.Sum(Worksheets(2).Range(addr), Worksheets(3).Range(addr))
  Worksheets("Sheet1").Range(addr) = x
End Sub