Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a border around merged cells vba

So I have a merged cell that looks like below

enter image description here

Following is my code for putting a border around it:

 Dim c As Range

 For Each c In testing  
      If c.MergeCells Then
           c.Interior.ColorIndex = 19
           c.Borders.LineStyle = xlContinuous
           c.Borders.Weight = xlThick
           c.Borders.Color = vbGreen
       End If
   Next

This code only creates a border around the top left cell (see picture). How do I ensure that the border is placed around the entire merged cell?

like image 747
sukhvir Avatar asked Aug 14 '16 09:08

sukhvir


People also ask

How do I add a border to a merged cell in Excel?

Border can be applied by setting LineStyle and Color property of IBorders to the merged range.

How do I change the cell border in Excel VBA?

VBA Border Property First, you need to specify the range or the cell where you wish to apply the border using the range object. After that, type a dot (.) and then select the “Borders” property from the list of properties and methods. Next, specify the border index from the contants avaiable.

How do I change the border color in Excel VBA?

Change Border Color Using Format Cells DialogSelect the cells with the borders requiring color change. Press Ctrl + 1 to launch the Format Cells dialog box or click the arrow with the border icon in the Home tab's Font Select More Borders… from the menu.

Does VBA work with merged cells?

In VBA, there is a “MERGE” method that you can use to merge a range of cells or even multiple ranges into one. This method has an argument “Across” which is optional. If you specify TRUE it will merge each row in the range separately, and if you specify FALSE it will merge the entire range as one.


2 Answers

You have to use the MergeArea of the referenced range.

Dim c As Range

For Each c In testing  
   If c.MergeCells Then
       With c.MergeArea
            .Interior.ColorIndex = 19
            .Borders.LineStyle = xlContinuous
            .Borders.Weight = xlThick
            .Borders.Color = vbGreen
       End With 
   End If
 Next
like image 123
winghei Avatar answered Oct 07 '22 02:10

winghei


Try

With c        'Range of the merged cell
    .BorderAround , Weight:=xlMedium
    .Borders.Color = vbGreen
End With
like image 27
Anastasiya-Romanova 秀 Avatar answered Oct 07 '22 04:10

Anastasiya-Romanova 秀