摘要:我有一个使用for each
循环在A列中循环的策略编号列表
问题:一切正常,除非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"))
在预先感谢您的帮助! :)
答案 0 :(得分: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
删除空白后, THEN 为其他检查执行循环。
答案 1 :(得分:3)
我假设你只关心theCell,如果它不是空的。这是对代码的更新,为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