VBA代码运行不一致

您好,我有这个代码,允许在一个工作表中的单元格被删除,此后,删除将在另一个工作表中更新。 这段代码一直运行良好,直到今天,当我再次尝试它不断给我错误在Set delRange = Union(delRange, .Cells(j, i)) 。 错误信息是“object_'Global'failed”的“Method'Union”我在其他工作簿上试过了,一开始工作,随后又给出了同样的错误。 我可以知道为什么我得到这个错误,并有任何解决scheme来debugging?谢谢

 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 

在不同的工作表范围内的Union是不允许的,所以如果find"#REF!" ,代码就会失败"#REF!" 在2张不同的床单。

移动:

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

之前:

 Next k