问题
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 keyboard shortcut to activate AddServiceNote and the code inserts a comment with standardized formatting and text.
Everything works, but it is not repeatable. I can't select another cell and add another comment using the same keyboard shortcut.
I can use another keyboard shortcut to activate FormatNotes where all the comments are formatted. Mysteriously, that reactivates my ability to insert another single standardized comment with AddServiceNote.
Am I missing something obvious? Why can't I insert comments over and over? Does this have to do with Set Note = ActiveCell.Comment?
Public Note As Comment
Public Sub AddServiceNote()
If Note Is Nothing Then
ActiveCell.AddComment
Set Note = ActiveCell.Comment
Note.Text "Function: "
OrganizeElements
End If
End Sub
Public Sub FormatNotes()
For Each Note In ActiveSheet.Comments
OrganizeElements
Next
End Sub
Public Sub OrganizeElements()
Note.Shape.TextFrame.AutoSize = True
'and a long list of other attributes
End Sub
回答1:
Whats happening is this:
- You have a Module Scope variable,
Note. Its value persists. - The first time you run
AddServiceNote,Note Is Nothingis TRUE, so theIf Thencode runs - In that
Ifcode,NoteisSetto something - The next time you run
AddServiceNote,Note Is Nothingis FALSE, so theIf Thencode does not run - Running
FormatNotesexecutes aForloop, settingNoteon each iteration - After the last iteration of the
Forloop,Noteis left asNothing(that's a side effect of theFor) - So, having run
FormatNotes,AddServiceNotewill work again (once)
The fix is simple
- move the
Dim Note As ...insideAddServiceNote(there is nothing about the code posted that requiredNoteto be Module Scoped) - Change
OrganizeElements's signature toPublic Sub OrganizeElements(Note As Comment) - Change the lines taht call
OrganizeElementsto passNoteas 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
回答2:
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
来源:https://stackoverflow.com/questions/60289557/confusing-vba-comment-insertion-behavior-in-excel