Home » excel » comments – AddComment on multiple sheets vba Excel

comments – AddComment on multiple sheets vba Excel

Posted by: admin March 9, 2020 Leave a comment

Questions:

The AddComment syntax works on first selected sheet in workbook, but for the next one gives me this error: Error 1004 “Application-defined or Object-defined error”. I do not know why crashes if multiple sheets were selected and works only for the first selected one. Does anyone have some idea?

 If selectedSheet.Cells(7, columnIndex).value <> 100 Then
           selectedSheet.Cells(7, columnIndex).Interior.ColorIndex = 3

           If standardReportFilePath <> "" Then 'not using the Standard Report Evalution algorithm
                        If VerifyStandardReportFile(selectedSheet.Name, selectedSheet.Cells(1, columnIndex).value, wbk, amplitude, missingCrashes) = True Then
                                selectedSheet.Cells(1, columnIndex).Interior.ColorIndex = 36 ' color the crash cell with yellow
                                Set rng = selectedSheet.Cells(1, columnIndex)
                                If rng.Comment Is Nothing Then
                                    **rng.AddComment "In Standard Report this crash starts to deploy from " & CStr(amplitude) & " amplitude"**
                                Else
                                    rng.Comment.Text "In Standard Report this crash starts to deploy from " & CStr(amplitude) & " amplitude"
                                End If
                            End If
                        End If
                    End If
                End If

An alternate set of code that shows the problem. (Run this with three blank worksheets in a new workbook.):

Sub test()
    Dim ws As Worksheet
    Dim Rng As Range

    'Running code with a single sheet selected
    Worksheets("Sheet1").Select

    'Code that shows issue - this will work
    Set ws = Worksheets("Sheet2")
    Set Rng = ws.Cells(1, 1)
    If Rng.Comment Is Nothing Then
        Rng.AddComment "xxx"
    End If

    'Get rid of comment again
    Rng.Comment.Delete

    'Running code with multiple sheets selected
    Worksheets(Array("Sheet1", "Sheet2", "Sheet3")).Select

    'Code that shows issue - will crash on the "AddComment"
    Set ws = Worksheets("Sheet2")
    Set Rng = ws.Cells(1, 1)
    If Rng.Comment Is Nothing Then
        Rng.AddComment "xxx"
    End If

End Sub
How to&Answers:

I found a workaround, but still don’t know why this problem even happens. For some reason error occurs when you have more then one worksheet selected. The solution is… To select one sheet before adding comments with someSheet.Select. At the end of macro you can try to select all previously selected sheets again if needed.

Answer:

What I do understand – thanks to Yoweks comment – is:
You are looping through all the selected sheets, check something, set comments (giving you the problems, because it does’nt work with more than one selected sheet) and want the previosly selected sheets to be selected afterwards.

You can save the previosly selected sheet in a variable, select one of them, run your code and then select all previosly selected sheets again. PLease try the following code:

Sub Comments()
Dim WsArr As Sheets, WS As Worksheet, ColIdx As Long
ColIdx = 7
Set WsArr = ActiveWorkbook.Windows(1).SelectedSheets
    WsArr(1).Select
    For Each WS In WsArr
        '*** your logic
        Set Rng = WS.Cells(1, ColIdx)
        If Rng.Comment Is Nothing Then
            Rng.AddComment "In Standard Report this crash starts to deploy from " & CStr(amplitude) & " amplitude"
        Else
            Rng.Comment.Text "Changed T"
        End If
    Next WS
    WsArr.Select
End Sub

Answer:

From the Excel documentation

You can add notes to individual cells by using comments

You can see in the ‘Review’ tab within Excel that, when you select multiple sheets, you cannot create a comment. I assume this is to do with Excel’s internals determining which cell should have a comment assigned to it.


Here is a function which you can call to assign a comment to a given cell, even if you have multiple sheets selected.

This sub also removes the need to test if a comment already exists, simply pass a new comment to a cell which already has one.

Sub UpdateComment(Rng As Range, Cmnt As String)
    Application.ScreenUpdating = False
    ' Get currently selected sheets
    Dim mySheets As Sheets: Set mySheets = ThisWorkbook.Windows(1).SelectedSheets
    ' Set current selection to just one sheet: this is where error is avoided
    ThisWorkbook.Sheets(1).Select
    ' Set Comment, new if doesn't exist or changed if it does
    If Rng.Comment Is Nothing Then
        Rng.AddComment Cmnt
    Else
        Rng.Comment.Text Cmnt
    End If
    ' Tidy up: re-select sheets & enable screen updating
    mySheets.Select
    Application.ScreenUpdating = True
End Sub

Use it like so in your code:

' ... your previous code
Set rng = selectedSheet.Cells(1, columnIndex)
UpdateComment rng, "In standard report this crash starts to deploy from ..." 

To loop over all selected sheets

Dim sh As Worksheet
For Each sh In ThisWorkbook.Windows(1).SelectedSheets
    Set rng = sh.Cells(1, columnIndex)
    UpdateComment rng, "In standard report this crash starts to deploy from ..."
Next sh

Answer:

I had the same problem while trying to get a comments function to work so instead of trying to figure it out per scenario, I decided to do a general one; call as needed.

Sub General_Functions_Comments(InCell As Range, TxtComment As String, Optional IsMergedAnalyzed As Boolean)
Dim IsComment As Comment
Dim RangeFixedMerged As Range
    If InCell.MergeCells = False Or IsMergedAnalyzed = True Then ' 3. If InCell.MergeCells = False
    With InCell
    Set IsComment = .Comment
    If IsComment Is Nothing Then ' 1. If Iscomment Is Nothing
    .AddComment.Text Text:=TxtComment
    .Comment.Shape.TextFrame.AutoSize = True
    .Comment.Visible = False
    Else ' 1. If Iscomment Is Nothing
    If InStr(.Comment.Text, TxtComment) Then ' 2. If InStr(.Comment.Text, TxtComment)
    Else ' 2. If InStr(.Comment.Text, TxtComment)
    .Comment.Text .Comment.Text & Chr(10) & TxtComment
    .Comment.Shape.TextFrame.AutoSize = True
    .Comment.Visible = False
    End If ' 2. If InStr(.Comment.Text, TxtComment)
    End If ' 1. If Iscomment Is Nothing
    End With
    Else ' 3. If InCell.MergeCells = False
    Set RangeFixedMerged = InCell.Cells(1, 1)
    Call General_Functions_Comments(RangeFixedMerged, TxtComment, True)
    Set RangeFixedMerged = Nothing
    End If ' 3. If InCell.MergeCells = False
End Sub

In your code

If standardReportFilePath <> "" Then 'not using the Standard Report Evalution algorithm
                        If VerifyStandardReportFile(selectedSheet.Name, selectedSheet.Cells(1, columnIndex).Value, wbk, amplitude, missingCrashes) = True Then
                                selectedSheet.Cells(1, columnIndex).Interior.ColorIndex = 36 ' color the crash cell with yellow
                                Set Rng = selectedSheet.Cells(1, columnIndex)
                                If Rng.Comment Is Nothing Then
                                Call General_Functions_Comments(Rng, "In Standard Report this crash starts to deploy from " & CStr(amplitude) & " amplitude", True)
                                Else: Call General_Functions_Comments(Rng, "In Standard Report this crash starts to deploy from " & CStr(amplitude) & " amplitude", True)
                                End If
                            End If
                        End If
                    End If
                End If

*Aside question, why to set an if, else statement if both will do the same?

Answer:

I remember generally similar case (I could not do something from code), trying hard to solve it and finally I found that…

Note that if you have multiple sheets selected, “New comment” button on the ribbon is inactive, so you just can’t do it from code if you cannot do it manually.
Why? – don’t ask me. I see a nice workaround above, which seems to be the only way to achieve what you need.