Excel VBA: Function applying to individual sheets

80 views Asked by At

I have a large number of worksheets that have the same layout, column G6:G38 is the years and Column H6:H38 is the corresponding amounts paid. I tried to create a simple formula that I could use in all the sheets that searches through these columns and sums the amounts in a given year. This is the function I wrote into a module:

Public Function TPaid(Year As Integer)
Application.Volatile
Dim x As Integer
x = 6
Do Until x = 38
    If Range("G" & x).Value = Year Then
    TPaid = TPaid + Range("H" & x).Value
    End If
    x = x + 1
Loop
End Function

After inserting the formula into individual cells on all the worksheets, I'm finding that each time I enter the formula, it causes all other uses of the same formula on the other worksheets to display that most recent calculation. How can I make the formula only apply to the sheet its entered into?

Example: on sheet1 in cell A1 I imputed =Tpaid(2013). then on sheet2 in cell A1 I imputed =Tpaid(2013). After hitting enter on sheet2 the amount displayed is correct, but now the amount in sheet1 has changed to display the same amount as in sheet2, which is incorrect.

1

There are 1 answers

0
usncahill On

As GSerg said, this can be done a couple of ways, the best of which is =SUMIF(G6:G38,2013,H6:H38).

Otherwise,

Public Function TPaid(Year As Integer)
  Application.Volatile
  Dim x As Integer, obj as Object
  With Application.Caller.Parent
    For x = 6 to 38
      If .Range("G" & x).Value = Year Then TPaid = TPaid + .Range("H" & x).Value
    Next
  End With
End Function