excel - vba 代码中的多个 Worksheet_Change 事件

标签 excel vba

我在合并两个 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/

相关文章:

sql - Excel VBA 中的 Microsoft Query - 如何传递日期过滤器

excel - VBA 在 ListFillRange ActiveX ComboBox 中存储字符串而不是范围

image - 使用VBA将Excel文件中的图片导出为jpg

excel - For Each - 在没有 for 的情况下编译错误

excel - 如何在 Excel VBA 中将文本附加到注释中?

excel - 打开网络目录上的文件

json - VBA:将 JSON 打印到文本文件包括双引号

java - 无法获得 JExcel/jxl 的正确编码

javascript - 如何格式化具有空行的 excel 文件以具有嵌套数组并匹配我需要呈现的 JSON 对象?

excel - 聚合、整理行并将行转置为列