Confusing VBA comment insertion behavior in Excel

后端 未结 2 1802
眼角桃花
眼角桃花 2021-01-29 03:42

I\'m going to rewrite this request. I see that I could be clearer.

From within the spreadsheet I highlight a cell where I want a standardized comment inserted. I use a k

相关标签:
2条回答
  • 2021-01-29 03:53

    Properly indenting the code makes it more obvious that the entirety of it in Sub CommentAddLabor only runs if there is no comment in the selected cell.

    You want:

    Public Sub CommentAddLabor()
        If Ct Is Nothing Then
            ActiveCell.AddComment
        End If
        Set Ct = ActiveCell.Comment
        CommentFormat 'calls the sub above
        Ct.Text "Function: " & Chr(10) & "Envision: " & Chr(10) & "Activity: " & Chr(10) & "Material: " & Chr(10) & "Duration: " & Chr(10) & "Consider: "
    End Sub
    
    0 讨论(0)
  • 2021-01-29 04:00

    Whats happening is this:

    • You have a Module Scope variable, Note. Its value persists.
    • The first time you run AddServiceNote, Note Is Nothing is TRUE, so the If Then code runs
    • In that If code, Note is Set to something
    • The next time you run AddServiceNote, Note Is Nothing is FALSE, so the If Then code does not run
    • Running FormatNotes executes a For loop, setting Note on each iteration
    • After the last iteration of the For loop, Note is left as Nothing (that's a side effect of the For)
    • So, having run FormatNotes, AddServiceNote will work again (once)

    The fix is simple

    • move the Dim Note As ... inside AddServiceNote (there is nothing about the code posted that required Note to be Module Scoped)
    • Change OrganizeElements's signature to
      Public Sub OrganizeElements(Note As Comment)
    • Change the lines taht call OrganizeElements to pass Note as a parameter:
      OrganizeElements Note
    Public Sub AddServiceNote()
        Dim Note As Comment
    
        If ActiveCell.Comment Is Nothing Then
            Set Note = ActiveCell.AddComment
            Note.Text Text:="Function: "
            OrganizeElements Note
        End If
    End Sub
    
    Public Sub FormatNotes()
        Dim Note As Comment
        For Each Note In ActiveSheet.Comments
            OrganizeElements Note
        Next
    End Sub
    
    Public Sub OrganizeElements(Note As Comment)
         Note.Shape.TextFrame.AutoSize = True
         'and a long list of other attributes
    End Sub
    
    0 讨论(0)
提交回复
热议问题