2

摘要:我有一个使用循环在 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"))

提前感谢您的帮助!:)

4

2 回答 2

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

删除空白后,然后循环进行其他检查。

于 2012-10-03T20:18:54.527 回答
3

我假设您只关心 theCell 如果它不为空。这是您的代码的更新,将 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
于 2012-10-03T20:05:11.060 回答