我需要将以下代码应用于一系列单元格(即B24:B28) - 如何进行编辑以实现此目的?
Private Sub Worksheet_Change(ByVal Target As Range)
Dim Oldvalue As String
Dim Newvalue As String
On Error GoTo Exitsub
If Target.Address = "$B$24" Then
If Target.SpecialCells(xlCellTypeAllValidation) Is Nothing Then
GoTo Exitsub
Else: If Target.Value = "" Then GoTo Exitsub Else
Application.EnableEvents = False
Newvalue = Target.Value
Application.Undo
Oldvalue = Target.Value
If Oldvalue = "" Then
Target.Value = Newvalue
Else
Target.Value = Oldvalue & ", " & Newvalue
End If
End If
End If
答案 0 :(得分:0)
If Target.Address = "$B$24"
这是您有兴趣修改的行。
如果您只希望在单个单元格上进行,则可能需要在其上方添加
If Target.CountLarge > 1 Then Exit Sub
现在我们知道它只是单击的单个单元格,我们可以使用intersect来保持代码简短并用
替换第一行If Not Intersect(Target, [B24:B28]) is Nothing Then
或者,我们可以用
替换单行If Target.Address = "$B$24" Or Target.Address = "$B$25" Or Target.Address = "$B$26" Or Target.Address = "$B$27" Or Target.Address = "$B$28"
但正如你所看到的那样,很快就会变得不那么优雅了。
我的建议 - 替换:
If Target.Address = "$B$24"
使用:
If Target.CountLarge > 1 Then Exit Sub
If Not Intersect(Target, [B24:B28]) is Nothing Then
最终代码变为:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim Oldvalue As String
Dim Newvalue As String
On Error GoTo Exitsub
If Target.CountLarge > 1 Then Exit Sub
If Not Intersect(Target, [B24:B28]) is Nothing Then
If Target.SpecialCells(xlCellTypeAllValidation) Is Nothing Then
GoTo Exitsub
Else: If Target.Value = "" Then GoTo Exitsub Else
Application.EnableEvents = False
Newvalue = Target.Value
Application.Undo
Oldvalue = Target.Value
If Oldvalue = "" Then
Target.Value = Newvalue
Else
Target.Value = Oldvalue & ", " & Newvalue
End If
End If
End If
将来,如果您想要更改Range
此影响,您只需修改[B24:B28]