AddComment导致应用程序定义或对象定义的错误

时间:2018-02-12 13:08:56

标签: excel vba excel-vba comments

我一直收到尝试使用.AddComment方法的错误消息,我尝试了各种表达式,但没有运气。目前我的代码是

Cells(cellRow, CellCol).Select
With Selection
    .Interior.color = vbRed
    .AddComment
        With .Comment
         .Text Text:helpfulComment
         .Shape.ScaleWidth 5.6, msoFalse, msoScaleFromTopLeft
         .Shape.ScaleHeight 1, msoFalse, msoScaleFromTopLeft
        End with
End With

错误信息读取,

  

运行时错误'1004' - 应用程序定义的错误或对象定义的错误

.Addcomment

上中断

1 个答案:

答案 0 :(得分:2)

及其'因为您无法在已有评论的范围内添加评论

所以你有两种方式

第一种方式 - 检查评论是否已经存在

Sub main()
    With Cells(cellRow, CellCol) 'reference wanted range
        .Interior.Color = vbRed
        If .Comment Is Nothing Then .AddComment ' Add a comment if not already there
        With .Comment ' reference the comment object of the referenced range
            .Text "Text: helpfulComment"
            .Shape.ScaleWidth 5.6, msoFalse, msoScaleFromTopLeft
            .Shape.ScaleHeight 1, msoFalse, msoScaleFromTopLeft
        End With
    End With
End Sub

第二种方式 - 无论如何都要清除评论(如果范围没有评论,则不会抛出任何错误)并在之后添加

Sub main()
    With Cells(cellRow, CellCol) 'reference wanted range
        .Interior.Color = vbRed
        .ClearComments ' Clear referenced range comments, if any
        With .AddComment ' add and reference a new comment object of the referenced range
            .Text "Text: helpfulComment"
            .Shape.ScaleWidth 5.6, msoFalse, msoScaleFromTopLeft
            .Shape.ScaleHeight 1, msoFalse, msoScaleFromTopLeft
        End With
    End With
End Sub