[英]Prevent cells from updating in VBA
the problem is the following, I want cell to update to current HH:MM:SS and change the interior color, as soon as I change the value in another control cell. 问题如下,我要在另一个控件单元中更改值后立即将单元格更新为当前的HH:MM:SS并更改内部颜色。
The code I have compiled for that purpose is the following: 我为此目的编译的代码如下:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
lRow = Range("F" & Rows.Count).End(xlUp).Row
Set MR = Range("F3:F" & lRow)
For Each Cell In MR
If (Cell.Value = "T") And (Time < Cells(Cell.Row, "E")) Then Cells(Cell.Row, "G").Interior.ColorIndex = 10
Cells(Cell.Row, "G").Value = Time
Next Cell
End Sub
However, what I get is the cells updating every time there is an action on the sheet while I want just a timestamp 但是,我得到的是每次在工作表上执行任何操作时单元格都会更新,而我只需要一个时间戳记
Change the event from Worksheet_SelectiontChange
to Worksheet_Change
. 将事件从
Worksheet_SelectiontChange
更改为Worksheet_Change
。 Worksheet_SelectiontChange
is used to detect when a new/different range/cell is selected. Worksheet_SelectiontChange
用于检测何时选择了新的/不同的范围/单元格。 Also, to limit to the change of a specific cell, just test the row and/or column of the provided Target
. 同样,为了限制特定单元格的更改,只需测试提供的
Target
的行和/或列。 I'll often use a Select Case
when I'm testing for multiple cells. 在测试多个单元格时,我经常会使用
Select Case
。
Private Sub Worksheet_Change(ByVal Target As Range)
Const COL_E = 5
Const COL_F = 6
Const COL_G = 7
If Target.Column = COL_F Then
Dim lRow As Long
lRow = Target.Row
If Cells(lRow, COL_F).Value = "T" Then
Cells(lRow, COL_E).Value = Time
Cells(lRow, COL_G).Interior.ColorIndex = 10
Else
' clear the data?
End If
End If
End Sub
It seems to me that VBA is completely unnecessary in your use case. 在我看来,在您的用例中完全不需要VBA。
Here's my suggestion: Unlock every editable cell in the Workbook, except for the control cell, add formula-based conditional formatting to your timestamp cell and protect the worksheet. 我的建议是:解锁工作簿中除控件单元格之外的所有可编辑单元格,将基于公式的条件格式添加到时间戳单元格中并保护工作表。
Much faster and easier to maintain. 更快,更容易维护。
Moved your Sub into the worksheet_change, reorganized the code (the Row.Count auto-find shouldn't be activated unless you are in the cells you want to be) And placed your variables in a stored condition array for easier updating. 将您的Sub移到worksheet_change中,重新组织代码(除非处于想要的单元格中,否则不应该激活Row.Count自动查找),并将变量放置在存储条件数组中以便于更新。
Private Sub Worksheet_Change(ByVal Target As Range)
Dim SC : SC = Split("3/6/T/E/G/10/F3:F/F", "/") 'Stored Conditions
If Target.Row = Cint(SC(0)) and Target.Column = Cint(SC(1)) Then
For Each Cell In Range(SC(6) & Range(SC(7) & Rows.Count).End(xlUp).Row)
If Cell.Value = SC(2) And Time < Cells(Cell.Row, SC(3)) Then
Cells(Cell.Row, SC(4)).Interior.ColorIndex = Cint(SC(5)) : Cells(Cell.Row, SC(4)).Value = Time
End If
Next
End If
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.