需要在excel中的代码按钮减去时间在单元格



有谁能帮帮我吗?我正在使用excel创建一个曲棍球模拟器,我需要一种方法(也许是一个按钮?)从游戏时钟中抽出时间。

例如单元格D4将在20:00开始,我需要一个按钮起飞:每次我点击它时,距离时钟20(20秒)。所以点击,时间会显示19:40,然后再点击按钮,时间会显示19:20,然后点击19:00,再点击18:40,等等。一直到0点。然后在下一段时间需要重置回20:00。

我认为按钮会起作用,但如果有不同的方式,只要它使游戏时钟下降:每次我需要它下降20秒,我就会感兴趣。

您可以从excel的开发人员菜单/工具箱中插入按钮到电子表格中。

您需要使用[m]:ss

将单元格设置为自定义格式

然后在你的按钮代码中你可以使用:

Sub ChangeGameClock()
Range("D4").Value = DateAdd("s", -20, Range("D4").Value)
If Range("D4").Value = "0" Then
Range("D4").Value = "0:20:00"
End If
End Sub
好运

尝试以下代码:

Option Explicit
Public Sub tmpSO()
'Set the cell to work on as cell D4 on the sheet
'   with the name Sheet1. You might have to change
'   the sheet name if your sheet is named differently.
Dim cell As Range
Set cell = ThisWorkbook.Worksheets("Sheet1").Cells(4, "D")
'Remove 20 seconds from D4
cell.Value2 = DateAdd("s", -20, cell.Value2)
's stands for seconds as outlined here:
'https://msdn.microsoft.com/en-us/library/office/gg251759(v=office.15).aspx
'If D4 is 0 or less then it should be reset to 20 minutes
If cell.Value2 <= 0 Then cell.Value2 = TimeSerial(0, 20, 0)
End Sub

如何使用上述代码:将代码复制到Excel文件的空模块中。然后,您可以向工作表添加一个新的(表单控件)按钮,并将上述宏(当前命名为tmpSO)分配给该按钮。如果您使用ActiveX按钮,则应在插入按钮后双击该按钮。然后VBE将弹出类似这样的内容:

Option Explicit
Private Sub CommandButton1_Click()
End Sub

改成

Option Explicit
Private Sub CommandButton1_Click()
'Set the cell to work on as cell D4 on the sheet
'   with the name Sheet1. You might have to change
'   the sheet name if your sheet is named differently.
Dim cell As Range
Set cell = ThisWorkbook.Worksheets("Sheet1").Cells(4, "D")
'Remove 20 seconds from D4
cell.Value2 = DateAdd("s", -20, cell.Value2)
's stands for seconds as outlined here:
'https://msdn.microsoft.com/en-us/library/office/gg251759(v=office.15).aspx
'If D4 is 0 or less then it should be reset to 20 minutes
If cell.Value2 <= 0 Then cell.Value2 = TimeSerial(0, 20, 0)
End Sub

之后,你的ActiveX按钮应该也工作了。

最新更新