2012-10-03 114 views
2

摘要:我有政策号码我是用for each环圈穿过列的列表需要ForEach循环对象错误

问题:一切正常,只是如果在列空单元格A,我的代码会删除整行(因为它应该),但是当我尝试设置policy变量时,我得到一个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")) 

在此先感谢您的帮助! :)

+1

+1格式良好且清晰的问题。 – nutsch

回答

6

这里有一个不同的方法来做你想做的。

退出循环。根据之前的实验,如果您使用for循环遍历行,则每次删除行时,最终会在删除行后跳过该行。另外,正如你所记录的,你删除的范围不能再被引用,因为你删除了它。

要删除所有基于第一列中的空行的代码更新这样的:一旦你删除的空白,THEN做你的循环为其他检查

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 

+0

这对我来说是最好的解决方案,因为我想使用For Each循环,而且我不必处理删除循环内部的空单元格。谢谢丹尼尔 –

+3

这是最好的解决方案,尽管您想先检查是否有空白单元格。否则,SpecialCells将导致错误。 –

+0

+1,使用'if application.worksheetfunction.countif(theRange,“”)> 0,然后使用Range.SpecialCells(xlCellTypeBlanks).EntireRow.Delete'来避免Doug提出的问题。 – nutsch

3

我假设你只关心cell,如果它不是空的。这里有一个更新你的代码,添加一个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 
+0

这确实有效,避免了对象错误。为了跳过循环迭代并转到下一个循环,我最终在我的Next之前放置了所有循环代码后的'end if'。但是,删除一行后,会跳过一行(我猜是因为行正在向上移动),如何避免这种情况? –

+1

你可以从底部开始往上走,但是你无法在每个循环中都做到这一点。更新我的代码以显示此内容。 – nutsch

+0

在使用不同的循环之前,我已经从底部走了,但在这种情况下,解决这个问题的方法是什么? –