根据另一个单元格的值在一个单元格中添加注释

Adding a comment in a cell based on another cell's value

我想在 Excel 中编写 ModuleSub 以便将评论添加到评论部分基于另一个单元格值的单元格。 例如:F2 Cell 的值是“High Level”,通过像 =GetComment(F2) 这样的函数,B2 cell 的注释部分改变了到“高级别”。

如果F2 的值为 空,则应将“无”添加到B2 单元格的注释部分。

下面的代码不起作用,我只是想说明我的意思

Function GetComment(ByVal target As Range, rng As Range)
    If IsEmpty(rng.Value) Then
        target.AddComment ("Nothing")
    Else
        target.AddComment (rng.Value)
    End If
End Function

为了更好地解释,我捕获了 excel 环境,您可以在下面的 link 中看到: https://s22.picofile.com/file/8448590268/IMG_20220324_WA0000.jpg

如果有人帮助我,我将不胜感激。提前致谢。

如果您不使用 UDF,那么您需要像那样更改您的代码

Option Explicit

Function GetComment(ByVal target As Range, rng As Range)
    If IsEmpty(rng.Value) Then
        myCmt target, "Nothing"
        'target.AddComment ("Nothing")   <= This code will fail if a comment already exists
    Else
        myCmt target, rng.Value
        'target.AddComment (rng.Value)   <= This code will fail if a comment already exists
    End If
End Function

Function myCmt(rg As Range, cmt As String)
' This will add  the string cmt as a comment to the target
' and will delete any existing comment regardless
    
    ' Just delete any existing comment
    If Not rg.Comment Is Nothing Then
        rg.Comment.Delete
    End If
    rg.AddComment (cmt)

End Function


Sub TestIt()
    GetComment [B2], [F2]
End Sub

在此 post 中,您找到了在这种情况下如何使用 UDF 的解决方法。