在 Excel 中使用 VBA 添加注释到单元格时出现运行时错误 1004

Nat*_*ii. 0 excel vba runtime-error

我在使用 VBA 将注释添加到 Excel 单元格范围时收到 Excel VBA 运行时错误 1004:应用程序定义或对象定义错误。

评论的文本来自用户表单:

    Description = TextBox1.Value
    StartTime = TextBox2.Value
    EndTime = TextBox3.Value


InputText = StartTime & " - " & EndTime & "  " & Description
MsgBox (InputText)
Run Code Online (Sandbox Code Playgroud)

这部分效果很好。然后有一些代码来格式化单元格。最后,VBA 应该为每个单元格添加注释。

Dim Cell As Range
For Each Cell In Selection
    Cell.AddComment
        Cell.Comment.Visible = False
        Cell.Comment.Text Text:=InputText  **'// ERRORLINE//**
    Next Cell
Run Code Online (Sandbox Code Playgroud)

我已经尝试更改一些代码,但没有任何运气:

Dim Cell As Range
For Each Cell In Selection
    'Cell.Comment.Delete
    Set Comment = Cell.Comment
        Cell.Comment.Visible = False
        Cell.Comment.Text Text:=InputText

        Next Cell
Run Code Online (Sandbox Code Playgroud)

没有任何问题的有效方法是:

Dim Cell As Range
For Each Cell In Selection
    'Cell.Comment.Delete
    Set Comment = Cell.Comment
        Cell.Comment.Visible = False
        Cell.Comment.Text Text:="InputText"

        Next Cell
Run Code Online (Sandbox Code Playgroud)

是什么导致了这个错误?

Dis*_*ame 5

在添加新评论之前清除评论:

For Each cell In Selection
    With cell
        .ClearComments
        .AddComment
        .Comment.Visible = False
        .Comment.Text Text:=InputText
    End With
Next cell
Run Code Online (Sandbox Code Playgroud)