2017-09-01 117 views
0

我想單擊一個單元格並運行一個宏以創建邊框,如果單元格沒有它,並且單元格具有邊框則會刪除邊框。但是當細胞合併時我無法做到。單擊合併單元格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 

有人可以請我給我解決這個問題。 謝謝。

回答

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 

當您單擊合併單元格,它認爲該範圍是左上角單元格。在我的代碼中,合併的單元格只是作爲「目標」傳遞的,它給了你需要的引用。

如果你想限制這隻有一些單元格,你可以通過地址過濾它。該

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形式有.AddressLocal:$ BottomRightCell,您可以在左上角單元的地址進行過濾,以確定哪些接受這種治療。

+0

感謝您answer.its工作,上創建邊界合併單元格,但是,如何爲此代碼創建條件僅適用於特定單元格,如L11和L12(我合併L11和L12)。 –

+0

啊! - 好。請參閱編輯。 – ainwood

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;)