1

I have a user-defined function in Excel that I run in multiple sheets. I am trying to use Cells(i, j) to pull the value of cells by their row and column in the sheet in which my function is called. Instead, Cells(i, j) pulls the value of cell [i,j] in the active sheet when I hit the 'Calculate Now' button, and auto-calculation does not work.

What am I doing wrong?

The full function is below, not sure if it's needed to answer my question.

Option Explicit
Option Base 1
Option Compare Text

Function recordString(ByVal width As Integer, ByVal height As Integer, ByVal firstCell As Range) As String
    Application.Volatile

    Dim tempString As String
    tempString = ""
    Dim i As Integer
    Dim j As Integer
    For i = firstCell.Row To firstCell.Row + height - 1
        For j = firstCell.Column To firstCell.Column + width - 1
            If IsEmpty(Cells(i, j)) Then
                tempString = tempString & "0"
            Else
                tempString = tempString & "1"
            End If
        Next j
    Next i
    recordString = tempString
End Function

1 Answer 1

1

You need to use Application.Caller.

This will return the value in cell A1 of the sheet the function is entered to:

Public Function DisplayCaller() As String

    DisplayCaller = Application.Caller.Parent.Cells(1, 1)

End Function

This will return the name of the calling sheet:

Public Function DisplayCaller() As String

    DisplayCaller = Application.Caller.Parent.Name

End Function

For more info:
http://www.cpearson.com/excel/sheetref.htm

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, thanks. That's what I get for thinking the Cells function would work intuitively.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.