VBA Error 91 after correct execution with for each

2019-08-16 15:12发布

I have the following code that works fine until the end of the MsgBox:

Sub CommentsAsFootnotes(myTemplate As Variant, ByRef footnotespage1 As String, ByRef footnotespage2 As String)
Dim rngTemp As Range
Dim rngComment As Range
Dim footnote As String
Dim i As Integer

    On Error Resume Next
    Set rngComment = myTemplate.Sheets("Seite 1 ").Range("B14:T35").SpecialCells(xlCellTypeComments)
    On Error GoTo 0
    i = 1
    'If rngComment is Nothing
        'Exit Sub
    'End If
    For Each rngTemp In rngComment
        rngTemp.value = rngTemp.value & CStr(i)
        rngTemp.Characters(Start:=Len(rngTemp.value), Length:=1).Font.Superscript = True
         MsgBox rngTemp.Comment.Text
        ' error thrown here
    Next rngTemp

    footnotespage1 = footnote

End Sub

The message box is shown with the correct content. However, when I click "OK", an error is thrown "Error 91, Object variable or with block variable not set" and the debugger highlights the line with the message box.

Do you have any idea what could cause this error?

1条回答
Anthone
2楼-- · 2019-08-16 15:30

It's because that current range doesn't have a comment inside, add an IF when the cell doesn't have any comment inside, like this :

If rngTemp.Comment Is Nothing Then
    MsgBox "No Comment found !"
Else
    MsgBox rngTemp.Comment.Text
End If
查看更多
登录 后发表回答