【问题标题】:Adding a comment in a cell based on another cell's value根据另一个单元格的值在单元格中添加注释
【发布时间】:2022-06-28 07:40:17
【问题描述】:

我想根据另一个单元格的值在一个单元格的评论部分添加评论。

例如:F2 cell的值为“High Level”,通过=GetComment(F2)之类的函数将B2 cell的评论部分改为“High Level” .

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

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环境截图:

【问题讨论】:

  • 这能回答你的问题吗? Using a UDF in Excel to update the worksheet
  • @Storax - 感谢您的回复,但它确实没有回答我的问题。我的确切问题是访问单元格的注释部分并根据另一个单元格的值更改它。
  • 根据帖子中的图片,您将函数GetComment 放入单元格B2 中,我假设您的期望是基于F2 中的值,B2 中的注释会相应地改变。所以,换句话说,你使用 UDF 来做到这一点,对吧?
  • @Storax - 是的,我的期望和你说的一样,我手动更改了单元格 B2 的注释以更好地显示我的目的。实际上单元格 B2 中的函数不起作用。

标签: excel vba function if-statement


【解决方案1】:

如果您不使用 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 的解决方法。

【讨论】: