简体   繁体   中英

Excel VBA Comment Query

So I have tried and failed many times to do this.

I'm trying to write a VBA script that when run will insert a comment in the active cell that says:

[Surname], [First Name] [Todays date] was [current cell value]

Surnames and First Names should be bold.

If the cell is edited again it would edit the comment and put the above format below the previous comment.

Here is what I have at the moment (bearing in mind it could be very wrong)

Sub Test()
Dim UserN As String
Dim commt As String
Dim cmt As Comment

UserN = Application.UserName
Set cmt = ActiveCell.Comment

If ActiveCell.Comment Is Nothing Then
commt = UserN & Chr(10) & Chr(10) _
  & Chr(10) & Format(Now, strDate) & " was £" & ActiveCell
With Selection

    With Cells(Selection.Row, Selection.Column)
    .ClearComments
    .AddComment
    .Comment.Visible = False
    .Comment.Shape.AutoShapeType = msoShapeRoundedRectangle
    .Comment.Text Text:=commt
        With .Comment.Shape.TextFrame
            ' Username
            With .Characters(1, Len(UserN)).Font
                .Bold = True
            End With

            With .Characters.Font
                .Size = 12
            End With
        End With
    .Comment.Shape.TextFrame.AutoSize = True
    End With
End With

Else

  commt.txt = commt.txt & Chr(10) UserN & Chr(10) & Chr(10)
  & Chr(10) & Format(Now, strDate) & " was £" & ActiveCell

With Selection

    With Cells(Selection.Row, Selection.Column)
    .ClearComments
    .AddComment
    .Comment.Visible = False
    .Comment.Shape.AutoShapeType = msoShapeRoundedRectangle
    .Comment.Text Text:=commt
        With .Comment.Shape.TextFrame
            ' Username
            With .Characters(1, Len(UserN)).Font
                .Bold = True
            End With

            With .Characters.Font
                .Size = 12
            End With
        End With
    .Comment.Shape.TextFrame.AutoSize = True
    End With
End With

End If

End Sub

I think the only major issue is with this line:

commt.txt = commt.txt & Chr(10) UserN & Chr(10) & Chr(10)
  & Chr(10) & Format(Now, strDate) & " was £" & ActiveCell

It is using the variable 'commt' as if it were a comment object, but is simply a string. It's also missing a '&' and a '_' line separator. I believe the line should be:

commt = cmt.text & Chr(10) & UserN & Chr(10) & Chr(10) & Chr(10) & Format(Now, strDate) & " was £" & ActiveCell

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM