如何使用过去日期更改单元格的值

时间:2015-04-21 10:44:51

标签: vba excel-vba access-vba excel

我正在尝试仅选择范围内的过去日期。因此,在B栏中,我需要所有具有日期之前的日期的单元格表示"日期已经消失"。我是一名初学者并尝试过这段代码,但它没有用。

Sub FilterDateBeforeToday()

Set rrg = "dd/mm/yyyy"

rrg = Range("b1:b2000")
If rrg = Now - 1 Then

ActiveCell.Value = "data already gone"

End If
End Sub

有人可以帮我吗?

4 个答案:

答案 0 :(得分:0)

只要所有B1:B2000都是日期。您将需要遍历每个单元格并检查它是否是之前的日期。

for i = 1 to 2000
    if range("B" & i).value < now - 1 then range("B" & i).value = "Data already gone"
next

如果您只是将其设置为activecell.value,那么在宏运行之前您所处的活动单元格将会发生变化。

答案 1 :(得分:0)

您可以遍历范围中的每个单元格,然后检查日期是否已过去。

Public Sub RemovePastDates()

Dim rng As Range, cell As Range

Set rng = ThisWorkbook.Worksheets(1).Range("B1:B2000")

For Each cell In rng
    If cell.Value <= Now - 1 Then
        cell.Value = "Date has passed"
    End If
Next cell

End Sub

请注意,我已明确引用了工作簿和工作表,以确保修改正确的工作表。

答案 2 :(得分:0)

Set rrg需要一个Range对象,而不是 Set rrg = "dd/mm/yyyy"

中的字符串 如果继续rrg = Range("b1:b2000")

Set将是正确的(我正在使用[]符号,这对于单个小区分配更简单,例如Set rrg = [A1] ...)

If rrg = Now - 1 Then ... rrg是一个范围......您需要为该范围内的每个单元重复If(例如,使用For Each。 ..见例子)

ActiveCell.Value = "data already gone" ...无论你的循环如何...... ActiveCell总是指当前光标位置的单元格

Sub FilterDateBeforeToday()
Dim MyRange As Range, MyCell As Range

    Set MyRange = Range([B1], [B1000])

    For Each MyCell In MyRange.Cells

        ' test if it contains a date ...
        ' on the 2nd pass we may have a string there already
        If VarType(MyCell) = vbDate Then

            ' use Int() to compare against today 00:00 hrs
            If MyCell < Int(Now()) Then
                MyCell = "Date passed"
            End If

        End If

    Next MyCell

End Sub

Now()返回日期加时间...当天的开头是Now(),小数部分被移除(Int())...所以一切都小于开头今天通过...这比< Now()-1更精确,这意味着比现在减去24小时。

答案 3 :(得分:0)

只需使用自动过滤器,无需循环:

Sub FilterDateBeforeToday()

With Range("B1:B2000")
    .AutoFilter 1, "<" & CLng(Date) '// Filter any dates before today
    .SpecialCells(12).Value = "Date already gone" '// Replace visible cells with text.
End With

ActiveSheet.AutoFilterMode = False '// Remove filter.

End Sub