简体   繁体   English

正确执行每个循环和单元格注释后出现VBA错误91

[英]VBA Error 91 after correct execution with for each loop and cell comments

I have the following code that works fine until the end of the MsgBox: 我有下面的代码可以正常工作,直到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. 但是,当我单击“确定”时,将引发错误“错误91,对象变量或未设置块变量”,并且调试器突出显示了带有消息框的行。

Do you have any idea what could cause this error? 您知道什么可能导致此错误吗?

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 ,如下所示:

If rngTemp.Comment Is Nothing Then
    MsgBox "No Comment found !"
Else
    MsgBox rngTemp.Comment.Text
End If

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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