[英]Looping through comments on an excel workbook in vba with merged cells
我有一本工作簿,里面有多張紙,上面有評論。 我必須遍歷每個工作表並選擇評論。 我已經實現了以下邏輯。
For Each Ip_Sheet In ActiveWorkbook.Worksheets
Set Rng = Ip_Sheet.Cells.SpecialCells(xlCellTypeComments)
If Rng Is Nothing Then
MsgBox "No comments in the sheet"
Else
For Each cell In Rng
Comment_Author_NameAndComment = Split(cell.Comment.Text, ":")
AuthName = Comment_Author_NameAndComment(0)
AuthComments = Comment_Author_NameAndComment(1)
如果工作表中沒有合並的單元格,則以上邏輯工作正常。 但是,如果存在合並的單元格/行,則“ For Each cell In Rng
的循環For Each cell In Rng
合並的單元格范圍中的For Each cell In Rng
運行。 例如,如果列A:D被合並,則循環將針對單元格A,B,C和D運行,並且我在AuthName
和AuthComments
變量中獲得相同的值。
我的問題是,如果找到合並的單元格,如何使循環跳至工作表上的下一條注釋?
編輯:我還嘗試通過以下方法循環遍歷工作表中的所有注釋,但是該方法不成功Rng.Comment
對象始終為空。
For Each cmnt_obj In Rng.Comment
cmt_txt = cmnt_obj.Text
Next cmnt_obj
由於SpecialCells(xlCellTypeComments)
返回合並范圍的所有單元格,因此您需要檢測某個單元格何時屬於命名范圍,並且僅處理其中一個單元格。 您可以使用Range.MergeCells
來檢測合並的單元格,並使用Range.MergeArea
返回合並的范圍本身。 然后,如果該單元格是合並范圍的左上角單元格,則僅報告注釋。
像這樣:
Sub Demo()
Dim rng As Range
Dim cl As Range
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ActiveWorkbook
For Each ws In wb.Worksheets
Set rng = ws.Cells.SpecialCells(xlCellTypeComments)
If Not rng Is Nothing Then
For Each cl In rng.Cells
If cl.MergeCells Then
If cl.Address = cl.MergeArea.Cells(1).Address Then
ReportComment cl
End If
Else
ReportComment cl
End If
Next
End If
Next
End Sub
Sub ReportComment(cl As Range)
Dim Comment_Author_NameAndComment() As String
Dim AuthName As String
Dim AuthComments As String
Comment_Author_NameAndComment = Split(cl.Comment.Text, ":")
AuthName = Comment_Author_NameAndComment(0)
AuthComments = Comment_Author_NameAndComment(1)
Debug.Print AuthName, AuthComments
'...
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.