我在合并两个 Worksheet_Change 事件时遇到问题 - 我可以从专家那里获得一些建议吗?
代码的目的是将单元格范围内的任何大写文本转换为小写,但显然我不能有两个事件。
我已经尝试将两者复制到同一个 Worksheet_Change 中,但 Excel 变得狂暴并崩溃。
范围 1:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim ccr As Range
Set ccr = Range("C6")
For Each Cell In ccr
Cell.Value = LCase(Cell)
Next Cell
End Sub
范围 2:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim acr As Range
Set acr = Range("C9:G9")
For Each Cell In acr
Cell.Value = LCase(Cell)
Next Cell
End Sub
非常感谢
最佳答案
主要问题是更改单元格值 Cell.Value
将触发另一个 Worksheet_Change
立即地。您需要 Application.EnableEvents = False
以防止这种情况。
我还建议使用 Intersect
因此代码仅在实际更改的单元格上运行。
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim AffectedRange As Range
Set AffectedRange = Intersect(Target, Target.Parent.Range("C6, C9:G9"))
If Not AffectedRange Is Nothing Then
Application.EnableEvents = False 'pervent triggering another change event
Dim Cel As Range
For Each Cel In AffectedRange.Cells
Cel.Value = LCase$(Cel.Value)
Next Cel
Application.EnableEvents = True 'don't forget to re-enable events in the end
End If
End Sub
除了@Frank Ball 的评论,包括错误处理:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim AffectedRange As Range
Set AffectedRange = Intersect(Target, Target.Parent.Range("C6, C9:G9"))
Application.EnableEvents = False 'pervent triggering another change event
On Error GoTo ERR_HANDLING
If Not AffectedRange Is Nothing Then
Dim Cel As Range
For Each Cel In AffectedRange.Cells
Cel.Value = LCase$(Cel.Value)
Next Cel
End If
On Error GoTo 0
'no Exit Sub here!
ERR_HANDLING:
Application.EnableEvents = True
If Err.Number <> 0 Then
Err.Raise Err.Number, Err.Source, Err.Description, Err.HelpFile, Err.HelpContext
End If
End Sub
关于excel - vba 代码中的多个 Worksheet_Change 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54672980/