Excel VBA单击单元格更改单元格的值 – 单独将其分配给多个范围

我正在尝试设置一个vba代码,这样我就可以点击一个特定数量的单元格,并让这些单元格在“nothing”,“cr”和“cv”之间切换。 到目前为止,我有这个在我的代码,但我需要分配给多个目标,但我似乎无法让他们独立工作。

Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range) Application.EnableEvents = False With Target If .Address = Range("A1").Address Then Select Case .Value Case "" .Value = "CR" Case "CR" .Value = "CV" Case "CV" .Value = "" Case Else .Value = "CR" End Select End If End With Range("A2").Select Application.EnableEvents = True End Sub 

这将是实现你想要的一种方法。

 Private Sub Worksheet_SelectionChange(ByVal Target As Range) ' 07 May 2017 Dim Rng As Range Set Rng = Range("A1,B2:B4,C3,D4") If Not Application.Intersect(Target, Rng) Is Nothing Then MsgBox "Cell " & Target.Address(False, False) & " was clicked." End If End Sub 

我注意到你的第一个Select语句是多余的,因为它和上一个是一样的。 🙂

枫叶,我并不完全确定,我完全理解你以后的事情,但这对我有效:

 Private Sub Worksheet_SelectionChange(ByVal Target As Range) Application.EnableEvents = False For Each T In Target With T 'If .Address = Range("A1").Address Then Select Case .Value Case "" .Value = "CR" Case "CR" .Value = "CV" Case "CV" .Value = "" Case Else .Value = "CR" End Select 'End If End With Next Range("A2").Select Application.EnableEvents = True End Sub 

如果这不是你想要完成的事情,我怀疑你可以很容易地适应你的需要。 希望这可以帮助。 如果您有任何问题,请不要犹豫。

这是我想出来的,它的效果很好。 感谢您的帮助。

 Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range) Application.EnableEvents = False If Target.Cells.Count = 1 Then If Not Intersect(Target, Range("C8:C10:C12:C14:C16:I8:I10:I12:I14:I16:O8:O10:O1:O14:O16:U8:U10:U12:U14:U16:AA8:AA10:AA12:AA14:AA16:AG8:AG10:AG12:AG14:AG16:AM8:AM10:AM12:AM14:AM16")) Is Nothing Then Select Case Target.Value Case "" Target.Value = "CR" Case "CR" Target.Value = "CV" Case "CV" Target.Value = "" Case Else Target.Value = "CR" End Select Range("B2").Select End If End If Application.EnableEvents = True End Sub