@sous2817 发布了一个很好的答案。我想扩展这个想法——但如果你喜欢这个方法,请给 @sous2817 的答案,因为我所做的只是稍微修改一下。
每当您重复代码时,最好考虑如何对其进行子程序化或将其部分转换为您可以使用和重用的函数。
这将您的代码分隔,使其更易读(通常),并且如果您的文件结构稍后需要更改代码,也许最重要的是使维护更容易。例如,您在两个子例程中有许多共同的元素:
sCheckAddress
表示范围地址的字符串变量
- 检查 target.cells.count 是否 = 1
- 检查目标是否与`sCheckAddress 相交
我将这些公共元素放在一个函数中,该函数告诉子例程何时对目标采取行动。虽然这在这个范围的项目中看起来微不足道,但在您处理更大和更复杂的 VBA 编程时养成一个好习惯。
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Application.EnableEvents = False
If UpdateCell(Target) Then `<~~ Use a custom function to determine whether to act on this cell.
With Target
.Font.Name = "Marlett"
.Value = "r"
.Offset(0, 1).Select
End With
End If
Application.EnableEvents = True
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Application.EnableEvents = False
If UpdateCell(Target) Then `<~~ Use a custom function to determine whether to act on this cell.
With Target
.Font.Name = "Marlett"
.Value = "r"
End With
End If
Application.EnableEvents = True
End Sub
这是检查以确保您Target
的范围只有一个单元格的函数。它还会执行第二次检查以确保与Target
您的sCheckAddress
. True
只有当它同时满足这两个条件时,它才会返回一个值,然后允许事件宏更新Target
.
Private Function UpdateCell(rng As Range) As Boolean
Const sCheckAddress As String = "B2:B80, D2:D80"
'Establish conditions that return "FALSE"
If rng.Cells.Count <> 1 Then Exit Function '<~~ Make sure only one cell triggered the event.'
If Intersect(Me.Range(sCheckAddress), rng) Is Nothing Then Exit Function '<~~ Make sure the cell is in your sCheckAddress Range.'
UpdateCell = True
End Function