ForEach循环对象需要错误

Mik*_*ogg 2 excel foreach vba excel-vba

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

问题:一切正常,除非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"))
Run Code Online (Sandbox Code Playgroud)

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

Dan*_*iel 6

这是一种不同的方式来做你想要的.

省去循环.从以前的实验中,如果使用for循环遍历行,则每次删除行时最终都会在删除行之后跳过该行.此外,正如您所注意到的,您删除的范围因为删除而无法再被引用.

要根据第一列删除所有空白行,请将代码更新为:

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
Run Code Online (Sandbox Code Playgroud)

一旦你删除了空白,然后你的循环进行其他检查.

  • 这是最好的解决方案,但您要先检查是否有空白单元格.否则,SpecialCells将导致错误. (3认同)