Consulting

Results 1 to 6 of 6

Thread: Why doesn't this work in a loop?

  1. #1

    Why doesn't this work in a loop?

    I'm using the following code to add comments to cells, or add to the existing comments in cells. For some reason, it will work fine the first time through, but not the second. Any ideas?

    [VBA]Sub CommentTest()
    Dim HasComment As Boolean
    Dim oldCmtStr As String
    Dim noteStr As String

    noteStr = "hey there"

    On Error Resume Next
    HasCommnet = ActiveCell.Comment.Parent.Address = ActiveCell.Address
    On Error GoTo 0
    If HasComment = True Then
    oldCmtStr = ActiveCell.Comment.Text
    ActiveCell.Comment.Text Text:=oldCmtStr & Chr(10) & noteStr
    Else
    ActiveCell.AddComment Text:=noteStr
    End If

    End Sub[/VBA]

  2. #2
    Administrator
    VP-Knowledge Base
    VBAX Grand Master mdmackillop's Avatar
    Joined
    May 2004
    Location
    Scotland
    Posts
    14,489
    Location
    Welcome to VBAX

    Add this line before your code
    [VBA]Option Explicit
    [/VBA]
    MVP (Excel 2008-2010)

    Post a workbook with sample data and layout if you want a quicker solution.


    To help indent your macros try Smart Indent

    Please remember to mark threads 'Solved'

  3. #3

    didn't work

    Thanks so much for the reply. Now however, it tells me the variable is not defined.

  4. #4
    Administrator
    VP-Knowledge Base VBAX Grand Master mdmackillop's Avatar
    Joined
    May 2004
    Location
    Scotland
    Posts
    14,489
    Location
    That is the purpose of Option Explicit. Check your spelling.
    MVP (Excel 2008-2010)

    Post a workbook with sample data and layout if you want a quicker solution.


    To help indent your macros try Smart Indent

    Please remember to mark threads 'Solved'

  5. #5
    VBAX Guru Kenneth Hobs's Avatar
    Joined
    Nov 2005
    Location
    Tecumseh, OK
    Posts
    4,956
    Location
    [VBA]Sub CommentTest()
    Dim CommentText As String
    Dim oldCmtStr As String
    Dim noteStr As String

    noteStr = "hey there"

    On Error Resume Next
    CommentText = Empty
    CommentText = ActiveCell.Comment.Text
    On Error GoTo 0

    If CommentText <> Empty Then
    oldCmtStr = ActiveCell.Comment.Text
    ActiveCell.Comment.Text Text:=oldCmtStr & Chr(10) & noteStr
    Else
    ActiveCell.AddComment Text:=noteStr
    End If

    End Sub[/VBA]

  6. #6

    Aah... Thank you.

    One was "HasCommnet" and the other was "HasComment". Thanks again.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •