Vba 为Target.Value2属性范围使用For循环时出现问题
在我的一本工作簿中,我在尝试使用Target.Value2属性将单元格值范围内的大小写更改为正确时,在工作表更改事件中遇到了一个问题 使用下面的代码,当我更改单个单元格时,案例将按预期更改为正确。粘贴多个单元格时,单步执行代码时,“局部变量”窗口中的每个值的大小写都会更改为“正确”,但粘贴到单元格中的值不是正确的大小写 提前谢谢Vba 为Target.Value2属性范围使用For循环时出现问题,vba,excel,Vba,Excel,在我的一本工作簿中,我在尝试使用Target.Value2属性将单元格值范围内的大小写更改为正确时,在工作表更改事件中遇到了一个问题 使用下面的代码,当我更改单个单元格时,案例将按预期更改为正确。粘贴多个单元格时,单步执行代码时,“局部变量”窗口中的每个值的大小写都会更改为“正确”,但粘贴到单元格中的值不是正确的大小写 提前谢谢 Option Explicit Private Sub Worksheet_Change(ByVal Target As Range) On Error GoTo
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
试试这个,你需要定义变量类型
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
你的回答很有魅力,谢谢你的帮助!我忘了一个定义的范围对一条记录有效。我根本不练习!将'Value=StrConvValue,vbProperCase'更改为'Target.Value2=StrConvValue,vbProperCase'在我的原始代码中也起作用。无论出于何种原因,在关闭并重新打开工作簿之前,我的代码一直在使用未声明的值。再次感谢!