简体   繁体   中英

Update Cell With Location of Last Edited Cell - Excel VB Error 28 “Out of stack space”

I am trying to essentially get one specific cell to update with the address of the most recently edited cell. I am running into the out of stack space error and I am not sure why. I'm guessing maybe a call isnt finishing and so it just fills the stack with each call?

I have the following code:

Worksheet Code

Private Sub Worksheet_Change(ByVal Target As Range)

    Call Module1.last_changed(Target)

End Sub

Module Code

Public LASTCHANGED As Range

Public Function last_changed(changedCell As Range)

    If LASTCHANGED Is Nothing Then
        Set LASTCHANGED = changedCell
    Else
        LASTCHANGED = changedCell
    End If

    Call last_changed_address

End Function


Public Function last_changed_address()

    Dim address As Variant
    address = Split(LASTCHANGED.address, "$")
    Sheet1.Range("A23").Value = address(1) + address(2)

End Function

I also have a global variable which will hold the location of the last edited cell. If there is a better way of doing this than a global variable I am open to discussion. Thanks!

You are getting the out of stack space error because you are re-triggering the Worksheet_Change event when you change the value of Range("A23") cuasing an indefinite loop. You need to toggle EnableEvents to break the chain.

This should replace all your code.

Private Sub Worksheet_Change(ByVal Target As Range)
    Application.EnableEvents = False

    Range("A23").Value = Target.address(False, False)

    Application.EnableEvents = True
End Sub 

Thank you Thomas, your code does exactly what I wanted the outcome to be. I just need to look into Scott's recommendation about storing variables in a reference sheet which I can access later.

I guess a parting question is, is there a way to do this without someone actually seeing the reference sheet show up?

Thanks for everyone's input I appreciate it!

To answer the original question, I used Thomas's code exactly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM