存在しないものを削除しようとする潜在的なエラーを処理するには、いくつかの方法があります。
まず、空白のセルがあるかどうかを確認できます。
with worksheets("Sheet1")
with .range(.cells(1, 1), .cells(rows.count, 1).end(xlup))
if cbool(application.countblank(.columns(1))) then
.cells.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
end if
end with
end with
'earlier version of Excel may not have COUNTBLANK
with worksheets("Sheet1")
with .range(.cells(1, 1), .cells(rows.count, 1).end(xlup))
if application.counta(.columns(1)) < .rows.count then
.cells.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
end if
end with
end with
上記には、.SpecialCells(xlCellTypeBlanks) メソッドによって完全に空白と見なされない一方で、 COUNTBLANK 関数が数式によって返された長さ 0 の文字列を空白としてカウントするという欠点があります。ただし、数式が入力されていることがわかっている列で空白を探すことはないでしょう。
次に、エラー処理メソッドを変更して、Nothingをテストできます。
dim delRng as range
with worksheets("Sheet1")
with .range(.cells(1, 1), .cells(rows.count, 1).end(xlup))
'temporarily suspend error handling
on error resume next
set delRng = .cells.SpecialCells(xlCellTypeBlanks)
on error goto 0
if not delRng is nothing then
delRng.EntireRow.Delete
end if
end with
end with
広く受け入れられていますが、私はこの方法を好みません。なぜなら、それが存在するかどうかを確認するために何かを壊す必要はないと思うからです。しかし、それは私の個人的な好みです。