我编写了下面的代码,它查看了CD列中的日期,如果任何给定单元格中的日期在今天日期之前(在H列中找到),则此单元格中的内容将被清除。但是,我希望代码能够在找到TodayDate之前的日期的行中清除多列(" CD:CT")中的内容。
有关如何扩展内容清算的任何建议?
Sub DeleteRange()
Dim i As Long
Dim numRowsWithVal As Long
Dim myActiveCell As Range
Dim todaysDate As Date
Worksheets("Sheet1").Activate
todaysDate = (Range("H" & Rows.Count).End(xlUp).Value)
numRowsWithVal = (Range("CD" & Rows.Count).End(xlUp).Row)
Set myActiveCell = ActiveSheet.Range("CD50")
For i = 0 To numRowsWithVal
Select Case True
Case myActiveCell.Offset(i, 0).Value <= todaysDate
myActiveCell.Offset(i, 0).ClearContents
End Select
Next
End Sub
答案 0 :(得分:0)
Intersect(Columns("CD:CT"), myActiveCell.Offset(i, 0).EntireRow).ClearContents
答案 1 :(得分:0)
您的代码中存在一些错误。它的外观如下(代码中的注释):
'ClearRange is better name for this subroutine, since it is not supposed to delete ranges but clear them instead.
Sub ClearRange()
Dim ws As Excel.Worksheet
Dim i As Long
Dim numRowsWithVal As Long
Dim myActiveCell As Range
'Dim todaysDate As Date
Set ws = Worksheets("Sheet1")
'You don't have to activate a worksheet to operate on its cells.
'Worksheets("Sheet1").Activate
'No need for that. There is VBA built-in function that returns today date.
'todaysDate = (Range("H" & Rows.Count).End(xlUp).Value)
numRowsWithVal = ws.Range("CD" & ws.Rows.Count).End(xlUp).Row
Set myActiveCell = ActiveSheet.Range("CD50")
For i = myActiveCell.Row To numRowsWithVal
'This is not the proper usage of Select Case.
'In Select Case you select between many available options. Here we can
'only two options - the date is earlier or later than today.
'In this case regular If statement is better choice.
' Select Case True
' Case myActiveCell.Offset(i, 0).Value <= todaysDate
' myActiveCell.Offset(i, 0).ClearContents
' End Select
If ws.Range("CD" & i).Value <= VBA.Date Then
Call ws.Range("CD" & i & ":CT" & i).ClearContents
End If
Next
End Sub