vba - 在特定条件下保持细胞不变

标签 vba excel cell

我正在寻找每次另一个单元格处于事件状态时在单元格中保留公式的方法。

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/

相关文章:

vba - 打开工作簿时,Workbook_Open 处理程序未在加载项中触发

arrays - 检查元胞数组是否是 Matlab 中另一个元胞数组的子集

excel - VBA Selenium with Chrome - 将文件上传到网页

debugging - 单步执行使用“运行应用程序”复制粘贴并执行的宏代码

excel - 双击处理事件后退出/禁用编辑模式

excel - Access VBA : how to return path of file you browsed to

excel - 需要一个查找功能来搜索一张纸的一列

excel - 为什么在 Excel/VBA 错误处理中 Err.Description 保持为空?

ios - 如何在选择时展开 UICollectionView 单元格而不弄乱 Collection View

cryptography - FPGA逻辑单元数量与性能的关系