首页 > 解决方案 > 在 Excel 中使用 VBA 向单元格添加注释时出现运行时错误 1004

问题描述

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

评论文本来自用户表单:

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


InputText = StartTime & " - " & EndTime & "  " & Description
MsgBox (InputText)

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

Dim Cell As Range
For Each Cell In Selection
    Cell.AddComment
        Cell.Comment.Visible = False
        Cell.Comment.Text Text:=InputText  **'// ERRORLINE//**
    Next Cell

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

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

没有任何问题的工作是:

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

是什么导致了这个错误?

标签: excelvbaruntime-error

解决方案


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

For Each cell In Selection
    With cell
        .ClearComments
        .AddComment
        .Comment.Visible = False
        .Comment.Text Text:=InputText
    End With
Next cell

推荐阅读