![](/img/trans.png)
[英]Using Nexted for loop to iterate through all cells in a worksheet and all worksheets in a workbook
[英]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.