通过更改变量来运行宏

时间:2017-05-09 15:22:09

标签: excel vba excel-vba

我现在可以根据当前日期和时间更改Active X微调器(“ Device1 ”)的范围。确定行号和确定列号的日期的时间。单元格(B3:H3)使用Today()函数返回日期,单元格(A3)每10秒返回当前时间。我已经使用了Offset()函数,但我现在意识到每次变量fDate或fTime发生变化时,微调器值都需要重置为0。这些是我目前正在使用的Subs。理想情况下,我希望只有在fDate和fTime从之前的值发生变化时才能调用 Sub SpinnerReset(),以避免每10秒重置一次。

如果不相等,也许可以保留以前的值并比较/运行?我不确定这是否可能。

Sub Device1_Change()
Dim fDate, fTime As Integer
'Change fDate based on day'
    If Range("B3") = Date Then fDate = 0
    If Range("C3") = Date Then fDate = 16
    If Range("D3") = Date Then fDate = 32
    If Range("E3") = Date Then fDate = 48
    If Range("F3") = Date Then fDate = 64
    If Range("G3") = Date Then fDate = 80
    If Range("H3") = Date Then fDate = 96
'Change fTime based on TimeStamp'
    If Range("A3") > TimeValue("09:59:59") And Range("A3") < TimeValue("11:00:00") Then fTime = 0
    If Range("A3") > TimeValue("10:59:59") And Range("A3") < TimeValue("12:00:00") Then fTime = 1
    If Range("A3") > TimeValue("11:59:59") And Range("A3") < TimeValue("13:00:00") Then fTime = 2
    If Range("A3") > TimeValue("12:59:59") And Range("A3") < TimeValue("14:00:00") Then fTime = 3
    If Range("A3") > TimeValue("13:59:59") And Range("A3") < TimeValue("15:00:00") Then fTime = 4
    If Range("A3") > TimeValue("14:59:59") And Range("A3") < TimeValue("16:00:00") Then fTime = 5
    If Range("A3") > TimeValue("15:59:59") And Range("A3") < TimeValue("17:00:00") Then fTime = 6
    If Range("A3") > TimeValue("16:59:59") And Range("A3") < TimeValue("18:00:00") Then fTime = 7
    If Range("A3") > TimeValue("17:59:59") And Range("A3") < TimeValue("19:00:00") Then fTime = 8
    If Range("A3") > TimeValue("18:59:59") And Range("A3") < TimeValue("20:00:00") Then fTime = 9
    If Range("A3") > TimeValue("19:59:59") And Range("A3") < TimeValue("21:00:00") Then fTime = 10
    If Range("A3") > TimeValue("20:59:59") And Range("A3") < TimeValue("22:00:00") Then fTime = 11
    If Range("A3") > TimeValue("21:59:59") And Range("A3") < TimeValue("23:00:00") Then fTime = 12

'Select cell for spinner'
Worksheets("Count").Range("C4").Offset(fTime, fDate).Value = Device1.Value
End Sub

Sub SpinnerReset()
Device1.Value = 0
End Sub

1 个答案:

答案 0 :(得分:0)

要详细说明我的评论,您的代码将如下所示。请注意,我只是编写了一个工作表名称(存储)和单元格(A1)。它可以是你想要的任何东西,如果愿意,你可以隐藏该表。

编辑:简化fDatefTime代码,并在“存储”单元格中包含“小时”。

Private Sub Device1_Change()

    Dim fDate As Long, fTime As Long

    'Change the sheet and cell to wherever you store the date
    'Note that the date will be stored as an Excel datecode
    With Sheets("Storage").Range("A1")
        If .Value <> Format(Now, "dd/mm/yy hh") Then
            SpinnerReset
            .Value = Format(Now, "dd/mm/yy hh")
        End If
    End With

    fDate = Evaluate("16*(MATCH(TODAY(),B3:H3,0)-1)")
    fTime = Evaluate("FLOOR(A3,1/24)*24-10")

    Sheets("Count").Range("C4").Offset(fTime, fDate).Value = Me.Device1.Value

End Sub