在我的一个工作簿中,当我尝试使用Target.Value2属性在一系列单元格值中将大小写更改为Proper时,我在Worksheet Change事件中遇到了一个问题。
使用下面的代码,当我更改单个单元格时,案例将按预期更改为“正确”。粘贴多个单元格时,在单步执行代码时,“局部”窗口中的每个值都会更改为“正确”,但粘贴到单元格中的值不是正确的大小写。
提前致谢!
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo Error:
If Not Intersect(Target, Range("I2:J999")) Is Nothing Then
If Target.Cells.Count = 1 Then
Application.EnableEvents = False
Target.Value = StrConv(Target.Value, vbProperCase)
Application.EnableEvents = True
Exit Sub
ElseIf Target.Cells.Count > 1 Then
Application.EnableEvents = False
Application.ScreenUpdating = False
For Each Value In Target.Value2
Value = StrConv(Value, vbProperCase)
Next Value
Application.ScreenUpdating = True
Application.EnableEvents = True
Exit Sub
End If
Exit Sub
End If
Exit Sub
Error:
Debug.Print Err.Description
If Application.ScreenUpdating = False Then Application.ScreenUpdating = True
If Application.EnableEvents = False Then Application.EnableEvents = True
Exit Sub
End Sub
答案 0 :(得分:0)
试试这个(你需要定义变量类型!)
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo Err
If Not Intersect(Target, Range("I2:J999")) Is Nothing Then
Application.EnableEvents = False
Application.ScreenUpdating = False
Dim cel as Range 'Define the type of variable formally Value
For Each cel In Target 'Will work for one cell or multiples
cel.Value = StrConv(cel.Value, vbProperCase)
Next cel
Application.ScreenUpdating = True
Application.EnableEvents = True
Exit Sub
End If
Exit Sub
Err:
Debug.Print Err.Description
If Application.ScreenUpdating = False Then Application.ScreenUpdating = True
If Application.EnableEvents = False Then Application.EnableEvents = True
Exit Sub
End Sub