Excell使用日期

时间:2017-10-25 22:41:52

标签: excel

我正在尝试预测收入,目前我有一个基本的电子表格。有2个变量不断变化,每当我更改它们时,整个电子表格都会发生变化,我不希望过去几天发生变化。

我的电子表格:

日期 24oct 25oct 26oct

收入 300 250 500

收入是x * y

变量x和y

如果我更改任何变量,它会改变整天,我不会发生这种情况,今天是25oct它应该改变这一天26oct而不是24oct。

这是一个简单的例子,真正的电子表格不是这样的,但我认为它足以看到我正在寻找的东西。

1 个答案:

答案 0 :(得分:0)

根据我的收集,您希望存储与今天(包括)之前的任何时间相关的收入值。这可以通过将值复制到单元格中,并保护它们免受编辑来实现。

以下代码检查日期范围是否小于或等于今天。如果是今天或前一天,它只复制日期和收入的值,并保护单元格免受编辑。

Sub UpdateProtection()

'Declare the range of dates
Dim Rng As Range
Set Rng = Range("A1:A4") 'Or whatever your range of dates is

'Set the time as the current time
MyTime = Date

'Loop through each cell in the range of dates
For Each Cell In Rng
    'If the date in the cell is less or equal to now, lock the cells
    If Cell.Value <= MyTime Then
        Cell.Formula = Cell.Text        'Copy the Date
        Cell.Locked = True              'Lock the Cell
        'Copy the value of the "Income"
        Cell.Offset(1, 0).Formula = Cell.Offset(1, 0).Value
        'Lock the associated income
        Cell.Offset(1, 0).Locked = True
    Else
        'Unlock the date if it's after today
        Cell.Locked = False
        'Unlock the associated "Income"
        Cell.Offset(1, 0).Locked = False
    End If
Next Cell

'Protect the sheet
Sheets("MySheetName").Protect

End Sub

这假设收入刚好低于日期。如果您希望每次更新工作表时都更新保护,则可以从Worksheet_Change事件中调用此子服务。

如果我误解了这个问题,或者遗漏了什么让我知道。