当我删除或清除获取调试消息的单元格的内容时

时间:2017-07-11 19:32:33

标签: excel vba excel-vba

我有一个VBA代码来大写我的大部分工作表但是当我删除或清除内容时,我收到调试消息。

任何帮助将不胜感激!

Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
If Not Intersect(Target, Range("A:Z")) Is Nothing Then
Target.Value = UCase(Application.Substitute(Target.Value, " ", ""))
End If
Application.EnableEvents = True
End Sub

1 个答案:

答案 0 :(得分:0)

如果您删除/更改/添加多个单元格,则Target不止一个单元格,您无法像操作那样将值设为大写。循环遍历目标和列A:Z的交集并使每个大写。

Private Sub Worksheet_Change(ByVal Target As Range)

    Application.EnableEvents = False
    If Not Intersect(Target, Range("A:Z")) Is Nothing Then
        dim rng as range
        for each rng in Intersect(Target, Range("A:Z"))
            rng.Value = UCase(Replace(rng.Value, chr(32), vbnullstring))
        next rng
    End If
    Application.EnableEvents = True

End Sub