单击合并单元格VBA

时间:2017-09-01 01:59:20

标签: excel vba excel-vba

我想点击一个单元格并运行一个宏来制作边框,如果单元格没有它,如果单元格有边框,它将擦除边框。但是当合并单元格时我无法做到。

此代码仅适用于普通单元格,如果我合并L11和L12则无法运行:

If Not Intersect(Target, Range("L11")) Is Nothing Then

        If ActiveSheet.Range("L11").Borders(xlEdgeBottom).LineStyle <> xlLineStyleNone And ActiveSheet.Range("L11").Borders(xlEdgeTop).LineStyle <> xlLineStyleNone Then

            'if has border erase it.
            ActiveSheet.Range("L11").Borders.LineStyle = xlNone


        Else

            'if doesn't have border create it.
            ActiveSheet.Range("L11").Borders.LineStyle = xlContinuous

        End If

我尝试使用相同的代码并更改范围,但单击时无法检测并为合并单元格创建边框。

If Intersect(Target, Range("$M$11:$N$11")) Is Nothing Then

有人可以给我解决这个问题。 谢谢。

2 个答案:

答案 0 :(得分:0)

我使用Worksheet_SelectionChange事件得到了一些工作:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Borders(xlEdgeBottom).LineStyle <> xlLineStyleNone And 
Target.Borders(xlEdgeTop).LineStyle <> xlLineStyleNone Then
    'if has border erase it.
    Target.Borders.LineStyle = xlNone
Else
    'if doesn't have border create it.
    Target.Borders.LineStyle = xlContinuous
End If
End Sub

单击合并的单元格时,它认为范围是左上角的单元格。在我的代码中,合并的单元格只是作为&#34; Target&#34;传递,它为您提供所需的参考。

如果要将此限制为仅限某些单元格,则可以按地址对其进行过滤。

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'//Filter to limit behavior to cell we want:
If InStr(1, Target.AddressLocal, "$L$11") Then      '//for a merged cell, .AddressLocal looks something like $L$11:$L$12
    If Target.Borders(xlEdgeBottom).LineStyle <> xlLineStyleNone And 
    Target.Borders(xlEdgeTop).LineStyle <> xlLineStyleNone Then
        'if has border erase it.
        Target.Borders.LineStyle = xlNone
    Else
        'if doesn't have border create it.
        Target.Borders.LineStyle = xlContinuous
    End If
End If
End Sub

因为合并的单元格具有$ TopLeftCell:$ BottomRightCell形式的.AddressLocal,所以您可以过滤左上角单元格的地址,以确定哪些获得此处理。

答案 1 :(得分:0)

使用大部分代码,一个简单的单行就可以解决这个问题:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  If Not Intersect(Target, Range("L11")) Is Nothing Then Range("L11").MergeArea.Borders.LineStyle = (Range("L11").MergeArea.Borders.LineStyle = 1) + 1
End Sub

你错过了Range.MergeArea;)