How to trigger VBA code after adding a comment?

为君一笑 提交于 2020-01-25 08:46:06

问题


Say if you add a comment to a cell which includes the word "today", then we would like a VBA code to be tiggered to replace the "today" with today's date in that comment. But the problem here is that I could not find an event (or any other way) to know when a comment has been added, or to which cell (range object). Any ideas?

My current stupid solution is to add VBA code inside Worksheet_SelectionChange event (it's a shame that I could not get the old location before the selection change), and then do a For Each loop, check each comment in the sheet, then execute that replacement.


回答1:


a workaround could be using a "helper" cell to store the address of the last selected cell so that once the user is done with the comment and selects another cell the event handler would check the "last" cell only

something like what follows (I used cell "A1" as "helper")

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim cmt As Comment

With Target
    If .Address <> Cells(1, 1) Then
    Set cmt = Range(Cells(1, 1)).Comment
        If Not cmt Is Nothing Then
            With cmt
                .Text (Replace(.Text, "today", Date))
            End With
        End If
    End If
End With

Cells(1, 1) = Target.Address

End Sub


来源:https://stackoverflow.com/questions/36101227/how-to-trigger-vba-code-after-adding-a-comment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!