我需要Excel中的宏来自动大写在一系列单元格中输入的文本。
我在网上找到了行得通的代码:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not (Application.Intersect(Target, Range("A1:C10")) _
Is Nothing) Then
With Target
If Not .HasFormula Then
Application.EnableEvents = False
.Value = UCase(.Value)
Application.EnableEvents = True
End If
End With
End If
它可以正常工作,但是当我将多个单元格复制或粘贴到指定范围内时,出现值不匹配错误。因此,我尝试改用以下代码:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim r As Range
Set r = Range("$A$1:$C$10")
Application.EnableEvents = False
For Each r In Target
If Not r.HasFormula And r.Value <> "" Then
r.Value = UCase(r.Value)
End If
Next
Application.EnableEvents = True
End Sub
即使复制和粘贴,此代码也可以完美地工作,但是即使r
变量上设置了一个范围,它也适用于整个电子表格。为什么?谢谢!
答案 0 :(得分:2)
您只需要适当地结合两个代码示例的技术即可。第二个代码缺少交集功能,而第一个代码则缺少一系列插入单元格之间的迭代。试试这个:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim Magic_Range As Range, Iterator_Range As Range
Set Magic_Range = Range("$A$1:$C$10")
Application.EnableEvents = False
If Not Application.Intersect(Target, Magic_Range) Is Nothing Then
For Each Iterator_Range In Application.Intersect(Target, Magic_Range)
If Not Iterator_Range.HasFormula And Iterator_Range.Value <> "" Then
Iterator_Range.Value = UCase(Iterator_Range.Value)
End If
Next Iterator_Range
End If
Application.EnableEvents = True
End Sub