2015-05-29 71 views
1

我試圖從一組工作簿和工作表中提取所有標題字段及其註釋。我試圖找到所有鎖定的單元格,而不是空的,並沒有計算。我已經把這段代碼放在一起,但是它在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 

回答

1

因爲Cell.Comment可以爲空,如果你想跳過拋出的任何錯誤,把一個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 
+0

擁有它應該返回一個空字符串值

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

試過了。它運行但不提取註釋 – Tom

+0

和'Db.Cells(i,4)'不爲空? 「Debug.Print cell.Comment.Text」返回什麼? –

+0

我剛剛通過在單元格中添加註釋('SHIFT' +'F2')並下降到立即窗口範圍(「A1」)進行測試。Comment.Text'正常工作... –

3

或者你可以只是之前對其進行測試:

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

這是更好的:o我的解決方案是馬虎 –

0

我現在在linux機器上,無法嘗試代碼,但您是否嘗試過將cell.comment.text轉換爲條形碼克,因此即使它是空的,因爲它代表你的代碼將返回空的評論也如果不打算那麼你就需要添加

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