简体   繁体   中英

Excel VBA read cell comment

I'm working on a code to check if an Excel cell contain a specific threaded comment,

I can't understand why the first code gives me the error

"Object variable or With block variable not set"

Sub test()
    Dim R As Range
    Set R = Range("E10:E205")

    For Each R In R.Cells
        If R.CommentThreaded.Text = "3" Then
                MsgBox (R.Address)
        End If
    Next R
End Sub

while this code works fine:

Sub test()
    Dim R As Range
    Set R = Range("E10:E205")

    For Each R In R.Cells
        If Not R.CommentThreaded Is Nothing Then
            If R.CommentThreaded.Text = "3" Then
                MsgBox (R.Address)
            End If
        End If
    Next R
End Sub

If the the cell R has no CommentThreaded object. Then of course a non-existing R.CommentThreaded cannot have a .Text property.

That is why you first need to check if R.CommentThreaded contains any comment object

If Not R.CommentThreaded Is Nothing Then

before you can use its .Text property.


Off topic:

In MsgBox (R.Address) you should remove the parenthesis MsgBox R.Address unless you really want to switch from submitting the argument as ByRef to submitting it ByVal .

Answer = MsgBox(R.Address)   'parentheses needed because = is used
Call MsgBox(R.Address)       'parentheses needed because 'Call' is used
MsgBox R.Address             'don't use perenthesis without =

but here the parenthesis do something completely different (note the extra space!):

MsgBox (R.Address)            'parenthesis here force ByVal!
      ^
      | Extra space!

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