Excel VBA单元格条件未得到满足

时间:2017-05-04 12:04:45

标签: excel-vba vba excel

我有以下电子表格片段:

enter image description here

当我按下昨天按钮时,我希望按钮找到所有具有“今天”或“明天”值的单元格,并将其替换为昨天,即=TODAY()-1

一旦解决了这个问题,其他两个按钮就变得微不足道了。

这是当前的宏:

Sub Yesterday_Click()
    Dim LastRow As Long
    Dim LastCol As Long
    Dim CellRange As Range

    Dim Today As String
    Dim Tomorrow As String
    Dim Yesterday As String

    Today = "=TODAY()"
    Tomorrow = "=TODAY()+1"
    Yesterday = "=TODAY()-1"

    'Find the last non-blank cell in column A(1)
    LastRow = Cells(Rows.Count, 1).End(xlUp).Row

    'Find the last non-blank cell in row 1
    LastCol = Cells(1, Columns.Count).End(xlToLeft).Column

    Set CellRange = Range(Cells(1, 1), Cells(LastRow, LastCol))

    For Each cell In CellRange
        If cell.Value = Today Or cell.Value = Tomorrow Then
            cell.Value = Yesterday
        End If
    Next cell
End Sub

如果我将观看添加到cell.Value,则cell.Value的结果为2015-05-04,而不是=TODAY()

如何让Excel评估我在单元格中写的内容,即=TODAY(),而不是单元格中公式所包含的值?

2 个答案:

答案 0 :(得分:0)

我不清楚你在天气里想要一个公式或一个值。

使用公式

cell.Formula = "=TODAY()"

或使用值

cell.Value = Evaluate("=TODAY()")

答案 1 :(得分:0)

Dim Yesterday As String

Today = "=TODAY()"
Tomorrow = "=TODAY()+1"
Yesterday = "=TODAY()-1"

'Find the last non-blank cell in column A(1)
LastRow = Cells(Rows.Count, 1).End(xlUp).Row

'Find the last non-blank cell in row 1
LastCol = Cells(1, Columns.Count).End(xlToLeft).Column

Set CellRange = Range(Cells(1, 1), Cells(LastRow, LastCol))

For Each cell In CellRange
    Debug.Print cell.Address
    Debug.Print cell.Value
    If cell.Value = Date Or cell.Value = Date + 1 Then
    cell.Formula = Yesterday
    End If
Next cell

End Sub