ForEach循环对象所需的错误

简介:我有一个策略编号的列表,我正在使用for each循环在列A中循环

问题:除了列A中有一个空单元格,我的代码删除整个行(应该是这样),除了当我尝试设置policyvariables时,我得到一个object required错误。 我在代码中标记了发生错误的位置。

问题:如何删除没有theCell丢失对象的空行?

代码:

 Dim theRange As Range Dim theSheet As Worksheet Dim theDate As String, policy As String, amount As String, details As String, entryDate As String Set theSheet = Sheets("OneDate") Set theRange = Range("A2:A" & theSheet.UsedRange.Rows.Count) For Each theCell In theRange 'FOR EACH POLICY IN COLUMN "A" If theCell.Value = "" Then theCell.EntireRow.Delete '<-- Row deleted here MsgBox (theCell.Value) End If policy = theCell.Value '<-- Error occurs here theDate = theCell.Offset(0, 1).Value theDate = UCase(Format(theDate, "ddMMMyy")) 

在此先感谢您的帮助! 🙂

这是一个不同的方式来做你想做的事情。

离开循环。 从以前的实验来看,如果循环使用for的行,每次删除一行时,最终都会在删除行之后跳过该行。 另外,正如你所logging的,你删除的范围不能再被引用,因为你删除了它。

要删除所有基于第一列的空白行,请将您的代码更新为:

 Dim theRange As Range Dim theSheet As Worksheet Dim theDate As String, policy As String, amount As String, details As String, entryDate As String Set theSheet = Sheets("OneDate") Set theRange = Range("A2:A" & theSheet.UsedRange.Rows.Count) 'Editted in some perfunctory error trapping incase of no blank rows. on error resume next debug.print theRange.SpecialCells(xlCellTypeBlanks).count on error goto 0 if err.number = 0 then theRange.SpecialCells(xlCellTypeBlanks).EntireRow.Delete end if 

一旦你删除了空白, 那么你的循环进行其他检查。

我假设你只关心细胞,如果它不是空的。 这里是你的代码的更新,添加一个Else到你的If结构

 Dim theRange As Range, lLastRow as long, lRowLoop as long Dim theSheet As Worksheet Dim theDate As String, policy As String, amount As String, details As String, entryDate As String Set theSheet = Sheets("OneDate") Set theRange = Range("A2:A" & theSheet.UsedRange.Rows.Count) lLastRow =cells(rows.count,1).end(xlup).row For lRowLoop=lLastRow to 2 step-1 'from last row to first row set theCell=cells(lRowLoop,1) If theCell.Value = "" Then theCell.EntireRow.Delete '<-- Row deleted here MsgBox (theCell.Value) Else policy = theCell.Value '<-- Error occurs here theDate = theCell.Offset(0, 1).Value theDate = UCase(Format(theDate, "ddMMMyy")) End If