Excel VBA单击单元格以激活宏 - 不使用合并单元格

时间:2017-10-24 12:52:29

标签: excel vba

我正在使用下面的代码在单击单元格时触发宏。有问题的单元是标题“Mitch的宏”,但它在合并的单元格B5到J5上。我已经尝试将这个合并范围命名为MITCH,但它仍然没有在点击运行...任何想法?提前谢谢!

Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Selection.Count = 1 Then
        If Not Intersect(Target, Range("MITCH")) Is Nothing Then
            MsgBox ("Hello World")
        End If
    End If
End Sub

3 个答案:

答案 0 :(得分:2)

问题是Selection.Count = 1。 合并的单元格有多个单元格,因此一旦您在合并区域中选择任何单元格,代码就不会被执行。

请试一试......

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Not Intersect(Target, Range("MITCH")) Is Nothing Then
        MsgBox ("Hello World")
    End If
End Sub

修改

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim rng As Range
    Set rng = Range("MITCH")
    If Target.CountLarge > rng.Cells.Count Then Exit Sub
    If Not Intersect(Target, rng) Is Nothing And Target.Cells(1).Address = rng.Cells(1).Address Then
        MsgBox ("Hello World")
    End If
End Sub

答案 1 :(得分:1)

经过一番思考后,我意识到大多数答案都有一些缺点,我认为这就是我们真正想要的:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim rng As Range
    Set rng = Range("MITCH")
    If Target.Address = rng.MergeArea.Address Then 'check if what's selected matches the named range entirely
        MsgBox ("Hello World")
    End If
End Sub

这会检查您选择的单元格是否完美映射到指定区域 - 特别是指定范围的 MergeArea

Intersect匹配只检查选择是否包含指定的范围

通过TL单元匹配意味着任何选择与命名范围相同的TL也将返回正数。例如,如果[B2:D3]是您合并的命名范围,那么[B2]匹配将在选择[B2:D3]时(如预期的那样)返回正数,但在选择[B2:XX100]时也会返回

当区域相同时,此代码仅返回正数,即仅选择合并的单元格。

答案 2 :(得分:0)

如果您已命名范围,则可以使用以下代码

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim tName As String
    On Error Resume Next
    tName = Target.Name.Name
    On Error GoTo 0
    If Len(tName) > 0 Then
        If tName = "MITCH" Then
            MsgBox ("Hello World")
        End If
    End If
End Sub