我正在寻找每次另一个单元格处于事件状态时在单元格中保留公式的方法。
Private Sub Worksheet_Change(ByVal Target As Range)
If ActiveSheet.Range("AL2").Value = 1 Then
ActiveSheet.Range("AK14").Value = ActiveSheet.Range("AL8").Value
Else
End If
End Sub
因此,如果单元格 AL2 等于 1(因此我想要的事件单元格),我希望单元格 AK14 中有某个值。 如果单元格 AL2 不等于 1,我只想保持 AK14 中的值不变(例如,有人可以覆盖它)。
目前 Excel 似乎迷失了第二部分:if AL2 = 0
并且我收到了错误。
如果我需要两个条件,我是否只需添加另一个 If 即可?
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
If Range("AL2").Value = 1 Then Range("F11").Value = Range("AK7").Value
Application.EnableEvents = True
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
If Range("AL2").Value = 2 Then Range("J11").Value = Range("AL7").Value
Application.EnableEvents = True
End Sub
所以我想要这两个宏..
最佳答案
当您在 Worksheet_Change
事件中更改单元格中的值时,您应该禁用这些事件。否则,它开始调用自身:
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
If Range("AL2").Value = 1 Then Range("AK14").Value = Range("AL8").Value
Application.EnableEvents = True
End Sub
<小时/>
然后,作为下一步,将 Error-catcher 与 .EnableEvents
一起使用确实是一个很好的做法:
Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo Worksheet_Change_Error
Application.EnableEvents = False
If Range("AL2").Value = 1 Then Range("AK14").Value = Range("AL8").Value
Application.EnableEvents = True
On Error GoTo 0
Exit Sub
Worksheet_Change_Error:
Debug.Print "Error " & Err.Number & " (" & Err.Description & ") "
Application.EnableEvents = True
End Sub
关于vba - 在特定条件下保持细胞不变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50170986/