2015-08-28 76 views
1

嗨,我有這個代碼,允許在一個表中的單元格被刪除,此後,刪除將在另一個表中更新。此代碼運行良好,直到今天,當我再次嘗試它不斷給我錯誤在 Set delRange = Union(delRange, .Cells(j, i))。錯誤消息是object_'Global'failed「的方法'聯盟' 我在其他工作簿上嘗試過它,並且一開始工作,隨後再次發出相同的錯誤。可我知道爲什麼會出現這個錯誤,請問有什麼解決方案來調試這個?謝謝VBA代碼運行不一致

Sub Database() 

Dim rng As Range, rngError As Range, delRange As Range 
Dim i As Long, j As Long, k As Long 
Dim wks As Worksheet 

On Error Resume Next 

Set rng = Application.InputBox("Select cells To be deleted", Type:=8) 

On Error GoTo 0 

If rng Is Nothing Then Exit Sub Else rng.Delete 

For k = 1 To ThisWorkbook.Worksheets.Count 'runs through all worksheets 

    Set wks = ThisWorkbook.Worksheets(k) 

    With wks 

    For i = 1 To 7 '<~~ Loop trough columns A to G 

     '~~> Check if that column has any errors 
     On Error Resume Next 

     Set rngError = .Columns(i).SpecialCells(xlCellTypeFormulas, xlErrors) 

     On Error GoTo 0 

     If Not rngError Is Nothing Then 
      For j = 1 To 100 '<~~ Loop Through rows 1 to 100 
       If .Cells(j, i).Text = "#REF!" Then 
        '~~> Store The range to be deleted 

      If delRange Is Nothing Then 
       Set delRange = .Cells(j, i) 

       Else 
      Set delRange = Union(delRange, .Cells(j, i)) 


        End If 
       End If 
      Next j 
     End If 

    Next i 

    End With 

Next k 

'~~> Delete the range in one go 
If Not delRange Is Nothing Then delRange.Delete 
End Sub 

回答

0

在不同的表範圍的Union是不允許的,所以如果發現"#REF!"在2代不同表的代碼將失敗。

移動:

If Not delRange Is Nothing Then delRange.Delete 
Set delRange = Nothing 

前:

Next k 
+0

當我把delRange =什麼,它給了我喜歡「對象變量或與塊變量未設置錯誤消息:刪除該行後,該代碼的作品,但給我一個對象所需的信息。我該怎麼辦?@ user3964075 – Niva

+0

@Niva對不起,修復明顯的錯誤。 – BrakNicku

+0

這樣想。謝謝 – Niva