簡體   English   中英

循環瀏覽每個打開的工作簿和工作表中的所有單元,並獲取評論

[英]Loop through all cells in every open workbook and worksheet and get comment

我正在嘗試從一組工作簿和工作表及其注釋中提取所有標題字段。 我正在嘗試查找所有鎖定,不為空且未計算的單元格。 我將這段代碼放在一起,但是在cell.comment.text行上引發了錯誤。 它返回錯誤:

Run-time error '91': Object Variable or With block variable not set

Sub extract()
Dim WB As Workbook
Dim ws As Worksheet: Dim Db As Worksheet
Dim NoRow As Integer: Dim i As Integer: Dim j As Integer
Dim cell

'   On Error GoTo extract_Error
Set Db = ThisWorkbook.Sheets("Data")

With Application
    .ScreenUpdating = False
End With

For Each WB In Application.Workbooks
    If Not WB.Name = ThisWorkbook.Name Then
        For Each ws In WB.Sheets
            i = Db.Cells(Db.Rows.Count, 1).End(xlUp).Row
            For Each cell In ws.UsedRange.Cells
                If cell.Locked = True And IsEmpty(cell) = False And cell.HasFormula = False Then
                    i = i + 1
                    Db.Cells(i, 1) = WB.Name
                    Db.Cells(i, 2) = ws.Name
                    Db.Cells(i, 3) = cell.Value
                    Db.Cells(i, 4) = cell.Comment.Text
                End If
            Next cell
        Next ws
    End If
Next WB

With Application
    .ScreenUpdating = True
End With

On Error GoTo 0
   Exit Sub

extract_Error:

MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure extract of Module Module1"
End Sub

或者您可以在之前進行測試:

If Not cell.Comment Is Nothing Then Db.Cells(i, 4) = cell.Comment.Text

因為Cell.Comment可以為null,所以如果要跳過引發的任何錯誤,請在其前面放一個On Error Resume Next ,可以始終將On Error GoTo 0放入以引發其他錯誤:

For Each WB In Application.Workbooks
   If Not WB.Name = ThisWorkbook.Name Then
       For Each ws In WB.Sheets
           i = Db.Cells(Db.Rows.Count, 1).End(xlUp).Row
           For Each cell In ws.UsedRange.Cells
               If cell.Locked = True And IsEmpty(cell) = False And cell.HasFormula = False Then
                   i = i + 1
                   Db.Cells(i, 1) = WB.Name
                   Db.Cells(i, 2) = ws.Name
                   Db.Cells(i, 3) = cell.Value
                   On Error Resume Next
                   Db.Cells(i, 4) = cell.Comment.Text
                   On Error GoTo 0
               End If
           Next cell
       Next ws
   End If
Next WB

如果要捕獲並打印錯誤,請執行以下操作:

Sub test()
    On Error Resume Next
    a = 5 / 0
    If Err.Number > 1 Then
        Debug.Print Err.Description
    End If
End Sub

編輯:正如@CmPi所建議-讓異常冒泡起來可能比實際提前測試情況要慢:

If Not cell.Comments Is Nothing Then
  Db.Cells(i, 4) = cell.Comment.Text
End If

我目前在Linux機器上,無法嘗試代碼,但是您嘗試將cell.comment.text轉換為字符串,因此即使它為空,它也應返回一個空字符串值

Db.Cells(i, 4) = CStr(cell.Comment.Text)

就目前情況而言,如果您不打算這樣做,您的代碼也將返回空注釋,那么您需要添加

if CStr(cell.comment.text) <> "" then
    Db.Cells(i, 4) = CStr(cell.Comment.Text)
end if

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM