用于显示WB(msgbox)中每个工作表的所有注释的vba代码

时间:2017-04-17 17:10:24

标签: excel vba excel-vba

我正在尝试编写子程序,以显示Activeworkbook MsgBox中每个工作表的所有注释文本(对于每个评论)。我的代码缺少一些使其工作的东西,但是现在它不会抛出错误,所以我知道我很接近。

任何人都可以帮助我吗?

Sub ShowAllWorkbookcomments()

On Error Resume Next

Dim ws As Worksheet
Dim rng As Range
Dim cell As Variant
Dim cmt As String
Dim commentcount As Integer

Set ws = ActiveWorkbook.Worksheets(1)
Set rng = ActiveSheet.Cells.SpecialCells(xlCellTypeComments)
commentcount = rng.Count
'cmt = ws.rng.Comment.Text

Dim varComment As String
Dim c As Comment

For Each ws In ActiveWorkbook.Worksheets

    Select Case commentcount
        Case 0
            MsgBox "No Comment", vbExclamation
            Resume Next
        Case Is > 0            
            For Each cell In rng
                varComment = c.Text
                MsgBox varComment, vbInformation
            Next cell
    End Select

    Set rng = Nothing            
Next ws    

End Sub

2 个答案:

答案 0 :(得分:2)

你很接近,只需要在Set rng = ActiveSheet.Cells.SpecialCells(xlCellTypeComments)循环中获取For Each ws In ActiveWorkbook.Worksheets

另外,添加了另一种方法来捕获工作表没有注释的可能性,并删除了不必要的Select Case

尝试以下代码:

Option Explicit

Sub ShowAllWorkbookcomments()

Dim ws As Worksheet
Dim rng As Range
Dim cell As Range
Dim cmt As String
Dim varComment As String

For Each ws In ActiveWorkbook.Worksheets
    On Error Resume Next 
    Set rng = ws.Cells.SpecialCells(xlCellTypeComments)
    On Error GoTo 0

    If Not rng Is Nothing Then '<-- current worksheet has comments
        For Each cell In rng.Cells
            'varComment = cell.Comment.text
            varComment = "worksheet " & ws.Name & " comment " & cell.Comment.text ' <-- added the worksheet name as reference 
            MsgBox varComment, vbInformation
        Next cell
    Else '<-- current worksheet has No comments >> rng is Nothing
        'MsgBox "No Comment", vbExclamation
        MsgBox "worksheet " & ws.Name & " has No Comments", vbExclamation ' <-- added the worksheet name as reference 
    End If
    Set rng = Nothing
Next ws

End Sub

答案 1 :(得分:0)

如以上注释之一所述,以上逻辑将导致为合并范围内的每个单元格显示MsgBox。以下逻辑将遍历给定工作表中的注释,它也适用于合并的行/列场景。

For Each CommentedSheets In ActiveWorkbook.Worksheets
    If CommentedSheets.Comments.Count = 0 Then
        MsgBox "worksheet " & CommentedSheets.Name & " has No Comments", vbExclamation
    Else
        For Each Individual_Comment In CommentedSheets.Comments
            varComment = "worksheet " & CommentedSheets.Name & " comment " & Individual_Comment.text
            MsgBox varComment, vbInformation