Using a function in a worksheet

tiredofit

Well-known Member
Joined
Apr 11, 2013
Messages
1,832
Office Version
  1. 365
  2. 2019
Platform
  1. Windows
This adds two numbers:

Code:
Function AddTwoNumbers(ws As Worksheet, rng1 As String, rng2 As String) As Integer
    
    AddTwoNumbers = ws.Range(rng1) + ws.Range(rng2)
    
End Function

and I can use it as follows:


Code:
Sub Add()


    Dim Result
    
    Result = AddTwoNumbers(Sheet2, "a1", "a2")
    
End Sub


but if I try to use it in a cell on a worksheet, such as:


Code:
=AddTwoNumbers(Worksheets("Sheet2"),"a1","a2")


it fails.


How can I adapt it?


Thanks
 
Last edited:

Excel Facts

Fastest way to copy a worksheet?
Hold down the Ctrl key while dragging tab for Sheet1 to the right. Excel will make a copy of the worksheet.
I don't think an excel sheet can use the worksheet object...

try this:


Code:
Function AddTwoNumbers(ws As String, rng1 As String, rng2 As String) As Integer
    
    AddTwoNumbers = Sheets(ws).Range(rng1) + Sheets(ws).Range(rng2)
    
End Function
 
Upvote 0
np. you might want to put in some error-checking in case the sheet doesnt exist.

Code:
Function AddTwoNumbers(ws As String, rng1 As String, rng2 As String)
    
    Dim WorksheetExists As Boolean
    Dim sht As Worksheet
    
    On Error Resume Next
    Set sht = Sheets(ws)
    On Error GoTo 0
    WorksheetExists = Not sht Is Nothing
    
    If WorksheetExists = True Then
        AddTwoNumbers = Sheets(ws).Range(rng1) + Sheets(ws).Range(rng2)
    Else
        AddTwoNumbers = "Sheet doesn't exist."
    End If
    
    
End Function


and maybe also for the ranges...
 
Upvote 0

Forum statistics

Threads
1,214,515
Messages
6,119,970
Members
448,933
Latest member
Bluedbw

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top