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

セルが空でない場合にのみ気にすることを想定しています。これがコードの更新であり、If構造にElseが追加されています

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 に答える