Microsoft Excel基于时间的数字增加

时间:2014-07-06 21:24:22

标签: excel excel-vba excel-formula vba

对于Excel 2013,是否有可能在特定时间内不断增加特定数字而不进行实际更改?例如,如果我希望Number 50每小时增加50;恩。 5:00 PM。下午6点,下午6点100.下午7点150等 感谢。

1 个答案:

答案 0 :(得分:0)

Sub TimeAddition()

Dim NowTime As Date
Dim Btime As Integer
Dim OffTime As Integer
Dim LR As Range
Dim IR As Range

'Set Ranges to a worksheet that will store
'your "static" variable information
'The reason you can't use a "Static" is they are reset
'whenever the workbook is closed

Set LR = Worksheets("Hidden").Range("A1")
Set IR = Worksheets("Hidden").Range("A2")

'Add your time interval between doing your task
dtime = Now() + TimeSerial(0, 0, 5)

'Set NowTime as the current time
NowTime = Now()

'If LR (Which is the last time the code ran, is empty, then this is the first
'run and set the last run time to the time now
If LR.Value = "" Then
LR.Value = Now()
End If

'If the current time is more than 15 seconds since the last time the code ran
'Then execute this section of the code. Your main task goes here
If NowTime >= (LR.Value + TimeSerial(0, 0, 15)) Then

Btime = Format((NowTime - LR.Value), "s") 'Workout the seconds between the times

OffTime = (Btime / 5) 'Divide the difference by 5, giving you an increment of 3 for every 5 seconds past

LR.Value = Now() 'Update LR (last time ran) to Now
IR.Value = IR.Value + OffTime 'Incremennt IR (your main value your interested in) by what was worked out
MsgBox "Updated IncVal, IncVal = " & IR.Value 'Output on message box (for testing)
End If

LR.Value = LR.Value 'Update Statics on sheet
IR.Value = IR.Value 'Update Statics On Sheet

Application.OnTime dtime, "TimeAddition" 'Schedule next run


End Sub

在代码中的注释中解释了它的工作原理。记得隐藏“隐藏”表。我经常使用这种方法,它永远不会让我失望。它在工作簿关闭时不会“更新”,但是一旦工作簿重新打开并相应更新,它将计算出已经过了多长时间

请根据您的需要进行编辑!