循环遍历每个打开的工作簿和工作表中的所有单元格,并获得评论

我试图从一组工作簿和工作表中提取所有的标题字段以及他们的评论。 我试图find所有locking的单元格,而不是空的,并没有计算。 我已经把这段代码放在一起,但是它在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 

因为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 

编辑:正如@CmPibuild议的 – 让一个exception冒泡可能比实际testing的情况下提前:

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

或者你可以在之前testing它:

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

我现在在linux机器上,不能尝试代码,但你有没有尝试将cell.comment.text转换为string,因此即使它是空的,它应该返回一个空string值

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

就目前而言,你的代码将返回空的评论,如果这不是意图,那么你需要添加

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