Vba excel добавить примечание к ячейке

Return to VBA Code Examples

This tutorial will demonstrate how to work with Cell comments in VBA.

The following code snippets show you how to add or delete a comment in a cell.

1. Put the following code somewhere in your macro to add a comment.

Sheet1.Range("A1").AddComment ("Hello World")

2. To delete a comment use this code

Sheet1.Range("A1").Comment.Delete

3. To edit a comment in a certain cell you need to read the existing comment and edit it. Use the code below

Dim OldComment As Variant
Dim NewComment As Variant

OldComment = Sheet1.Range("A1").Comment.Text
NewComment = OldComment & " Edited comment"
    
Sheet1.Range("A1").Comment.Delete
    
Sheet1.Range("A1").AddComment (NewComment)

First, you need to read the existing comment in OldComment variable.

After that you can edit a comment, e.g. add the new text to the existing one in NewComment variable.

Now, you need to delete the old comment and add the new one. In order to delete the comment, you have to use the .Comment.Delete command.

Finally, you can add the comment from the NewComment variable using the .AddComent command.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro – A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

alt text

Learn More!

Is there a way to activate a comment on a cell by hovering over it? I have a range of cells that I would like to pull respective comments from another sheet when hovered over each individual cell. The hover event would pull the comments from their respective cells in the other sheet.

The comments are of string value. Basically, I have a range of cells in Sheet 1, let’s say A1:A5 and I need comments to pop-up when I hover over them and pull from Sheet 2 range B1:B5. The reason why I won’t do it manually is because the contents of Sheet 2 change every day. That is why I am trying to see if there is a VBA solution.

asked Aug 9, 2017 at 21:09

studentofarkad's user avatar

studentofarkadstudentofarkad

1551 gold badge1 silver badge8 bronze badges

4

hovering over any cell, that contains a comment, shows that cell’s comment

this is how you add a comment to a cell and how you update the comment text

Sub aaa()
    With Range("E6")
        If Not .Comment Is Nothing Then .Comment.Delete
        .AddComment "this is a comment"
        .Comment.Text "abc123" 'No need the assignment sign "=" after .Comment.Text             
    End With
End Sub

Kristóf Nagy's user avatar

answered Aug 9, 2017 at 21:24

jsotola's user avatar

jsotolajsotola

2,2391 gold badge9 silver badges22 bronze badges

0

Try this code.

Sub test()
    Dim rngDB As Range, rngComent As Range
    Dim rng As Range
    Dim cm As Comment, i as integer
    Set rngComent = Sheets(1).Range("a1:a5")
    Set rngDB = Sheets(2).Range("b1:b5")

    For Each rng In rngComent
        i = i + 1
        If Not rng.Comment Is Nothing Then
            rng.Comment.Delete
        End If
        Set cm = rng.AddComment
        With cm
            .Visible = False
            .Text Text:=rngDB(i).Value
        End With
    Next rng

End Sub

answered Aug 10, 2017 at 4:20

Dy.Lee's user avatar

Dy.LeeDy.Lee

7,4771 gold badge11 silver badges14 bronze badges

2

A less bulky «All-in-One» solution:

Sub comment(rg As Range, Optional txt As String = "")
  If rg.comment Is Nothing Then
    If txt <> "" Then rg.addComment txt
  Else
    If txt = "" Then rg.comment.Delete Else rg.comment.text txt
  End If
End Sub

Usage:

Using cell [a1] as an example …but shortcut notation like [a1]) should generally be avoided except for testing, etc

  • Add or change comment: comment [a1], "This is my comment!"
  • Delete existing comment: comment [a1], "" or simply comment [a1]

Related stuff:

  • set comment box size:[a1].comment.Shape.Width = 15 and[a1].comment.Shape.Height = 15
  • set the box position: [a1].comment.Shape.Left=10 and [a1].comment.Shape.Top=10
  • change background box color: [a1].comment.Shape.Fill.ForeColor.RGB = vbGreen

Nowadays I think that comments (or «notes», as they’re now called) are hidden by default.

  • Always show all comments: Application.DisplayCommentIndicator=1

  • Show when mouse hovers over cell: Application.DisplayCommentIndicator=-1

  • Disable comments (hide red indicator): Application.DisplayCommentIndicator=0

  • show/hide individual comments like [a1].comment.visible=true, etc.

  • get comment text: a=[a1].comment.text

hornetbzz's user avatar

hornetbzz

9,1285 gold badges35 silver badges53 bronze badges

answered Nov 9, 2021 at 12:06

ashleedawg's user avatar

ashleedawgashleedawg

20k8 gold badges73 silver badges104 bronze badges

This code will refresh the contents of the comments every time you open the workbook. It is based on ranges of both destination as well as source. Make sure to first add a comment for the cell range first. You won’t need VBA for that.

Private Sub Workbook_Open()
    Dim ws As Worksheet
    Dim rg As Range
    Dim comment As String
    Dim i As Integer

i = 1
Set rg = Range("E1:E10") 'set range of where the comments will be seen
Set ws = Sheets("Sheet1")


For Each c In rg
comment = ws.Cells(i, 2).Value 'set location of comments you are grabbing from
c.comment.Text Text:=comment
i = i + 1
Next c
End Sub

Mathieu Guindon's user avatar

answered Aug 9, 2017 at 21:50

TJYen's user avatar

TJYenTJYen

3435 silver badges13 bronze badges

1

I’ve discovered that if the sheet cell is previously formatted and contains data the VBA Add Comments routines may not work. Also, you have to refer to the cell in the «Range» («A1») format, not the «Cells» (Row Number, Column Number) format. The following short sub worked for me (utilize prior to program formatting/adding data to cell):

Sub Mod01AddComment()

Dim wb As Workbook
Set wb = ThisWorkbook
Dim WkSheet As Worksheet
Set WkSheet = wb.Sheets("Sheet1")

Dim CellID As Range

Set CellID = WkSheet.Cells(RowNum, ColNum)
` ( or, Set CellID = WkSheet.Range("A1") )

CellID.Clear

CellID.AddComment
CellID.Comment.Visible = False
CellID.Comment.Text Text:="Comment Text"

End Sub

answered Nov 27, 2021 at 18:25

Alabama_Al's user avatar

Студворк — интернет-сервис помощи студентам

Здравствуйте.

Прошу вашей помощи, уважаемые эксперты. Сейчас пилю таблицу учета рабочей документации. Хочу реализовать такую фишку: при щелчке по ячейке определенного столбца появляется формочка, где пользователь расставляет галочки, нажимает ок, и в примечание этой ячейки добавляется информация в соответствии с поставленными галочками.

Все достаточно прозрачно, кроме момента с комментарием. Как его добавить я разобрался, использую команду ActiveCell.AddComment.Text («текст»). Но если щелкнуть по ячейке, которая уже содержит примечание, то появляется ошибка 1004. Хочу подразобраться с этим. В связи с этим несколько вопросов:
1. Как, собственно, записать новый комментарий взамен имеющегося?
2. Как сделать проверку на наличие комментария? То есть, если ячейка не содержит комментарий, то молча выполняется нужный код, если комментарий уже есть, вывести окошко типа «вы уверены?», при нажатии «да» выполняется код, при нажатии «нет» он, соответственно, не выполняется.
3. Можно ли вносить правку в существующий комментарий средствами VBA?

Прошу вас помочь, по ходу скорее всего появятся еще вопросы… заранее большое спасибо.


1 августа 2012,
VBA,
Konstantin

Создание примечания для ячейки в Excel с помощью макроса, которое также имело бы сложное внутреннее форматирование, не самая тривиальная задача. Для этого можно воспользоваться например таким кодом:

With Worksheets(1).Cells(4, 12).Comment
   .Visible = False
   .Text "Жирный шрифт:" & Chr(10) & "курсив"
   .Shape.DrawingObject.Characters(1, 13).Font.Bold = True
   .Shape.DrawingObject.Characters(15, 20).Font.Italic = True
End With

В итоге получится примерно такое примечание:

Форматированное примечание ячейки

Order_macros

2 комментария в “Создание форматированного примечания с помощью VBA”

Комментировать

Ну, приблизительно так  

  ‘Работа с комментариями  
‘1) меняем штрифт у комментария в заданной ячейке  
Range(«D10»).Comment.Shape.TextFrame.Characters.Font.Size  

  ‘2) изменяем размер окошка всех примечаний на листе ровно под текст (AutoSize)  
Sub All_Comments_Size_Change()  
Dim iComment As Comment  
   For Each iComment In ActiveSheet.Comments  
       iComment.Shape.TextFrame.AutoSize = True  
   Next iComment  
End Sub  

  ‘3) добавляем комментарий в ячейку и меняем его шрифт  
Sub ChangeFontInComment()  
   With Range(«B2»)  
       .ClearComments  
       .AddComment  
       .Comment.Text «бла-бла-бла»  
       With .Comment.Shape.TextFrame.Characters.Font  
           .Name = «Times New Roman»  
           .Size = 14  
           .Bold = True  
       End With  
   End With  
End Sub  

  ‘4) меняем шрифт у всех комментариев  
Sub All_Comments_Font_Change()  
Dim iComment As Comment  
   For Each iComment In ActiveSheet.Comments  
      With iComment.Shape.TextFrame.Characters.Font  
           .Name = «Times New Roman»  
           .Size = 14  
           .Bold = True  
       End With  
   Next iComment  
End Sub  

  ‘5) устанавливаем высоту и ширину окна примечания  
Sub Change_Size_Comment_Window()  
   With Range(«A1»)  
       .AddComment «Bla-bla-bla»  
       With .Comment.Shape  
           .Width = 100  
           .Height = 200  
           .Visible = True  
       End With  
   End With  
End Sub  

  ‘6) устанавливаем высоту и ширину для всех примечаний  
Sub Размер_Комментарий()  
Dim iComment As Comment  
   For Each iComment In ActiveSheet.Comments  
       iComment.Shape.TextFrame.AutoSize = True  
       iComment.Shape.Height = iComment.Shape.Height + 10  
       iComment.Shape.Width = iComment.Shape.Width + 15  
   Next iComment  
   MsgBox «Размеры комментарий исправлены!», vbInformation, «Комментарии»  
End Sub  

  ‘7 устанавливаем размер окна комментария AutoSize и меняем свойство окно на «Перемещать, но не именять размеры»  
Sub AutoSizeMoveDontChangeSizeComments()  
‘Свойство XlPlacement объекта Shape может быть одним из этих констант (Формат примечания/Свойства/)  
‘- xlFreeFloating — не перемещать и не изменять размеры  
‘- xlMove — перемещать, но не именять размеры  
‘- xlMoveAndSize — перемещать и изменять объект вместе с ячейками  
Dim iComment As Comment  
   For Each iComment In ActiveSheet.Comments  
       With iComment.Shape  
           .TextFrame.AutoSize = True  
           .Placement = xlMove ‘перемещать, но не именять размеры  
       End With  
   Next iComment  
   MsgBox «Все комментарии обработаны!», 64, «Конец»  
End Sub  

  ‘8 Добавление даты в комментарий  
Private Sub Worksheet_Change(ByVal Target As Range)  
   ‘если изменения в диапазоне A1:A10  
   If Not Intersect(Target, Range(«A1:A10»)) Is Nothing Then  
       ‘если выделили больше одной ячейке, то выход  
       If Selection.Cells.Count > 1 Then Exit Sub  
       Target.NoteText Text:=Application.UserName & Chr(10) & «Дата: » & Now  
   End If  
End Sub

Понравилась статья? Поделить с друзьями:
  • Vba excel добавить несколько строк
  • Vba excel добавить лист с именем
  • Vba excel добавить лист в конце книги
  • Vba excel добавить значение в массив
  • Vba excel добавит свою функцию