VBA to Add border around a block of cells based on each change in value for Col A

richardstory

New Member
Joined
Feb 24, 2023
Messages
4
Office Version
  1. 365
Platform
  1. Windows
Hi,

I'm looking for a simple VBA to loop adding a Thick (outside edge only) Border around a range of cells in a list (i.e. Col A to Col H) for the rows in which the value of Col A is the same, i.e. Rows 2-4="One", Rows 5-10="Two", therefore this would create the Border around range A2:H4, A5:H10 and so on.
NB (list is sorted by Col A so all like data is together)

Any assistance appreciated.
 

Excel Facts

How to show all formulas in Excel?
Press Ctrl+` to show all formulas. Press it again to toggle back to numbers. The grave accent is often under the tilde on US keyboards.
Give this a try with a copy of your workbook.

VBA Code:
Sub Add_Borders()
  Dim a As Variant
  Dim i As Long, j As Long, fr As Long
  
  With Range("A1", Range("A" & Rows.Count).End(xlUp).Offset(1))
    a = .Value
    fr = 2
    For i = 2 To UBound(a) - 1
      Do While a(i + j, 1) = a(i, 1) And i + j <= UBound(a)
        j = j + 1
      Loop
      .Cells(fr, 1).Resize(j, 8).BorderAround xlContinuous, xlThick, xlAutomatic
      fr = fr + j
      i = i + j - 1
      j = 0
    Next i
  End With
End Sub

My result:

1677582198418.png
 
Upvote 0
Solution
Sub Add_Borders() Dim a As Variant Dim i As Long, j As Long, fr As Long With Range("A1", Range("A" & Rows.Count).End(xlUp).Offset(1)) a = .Value fr = 2 For i = 2 To UBound(a) - 1 Do While a(i + j, 1) = a(i, 1) And i + j <= UBound(a) j = j + 1 Loop .Cells(fr, 1).Resize(j, 8).BorderAround xlContinuous, xlThick, xlAutomatic fr = fr + j i = i + j - 1 j = 0 Next i End With End Sub
thanks, just does the job.
 
Upvote 0

Forum statistics

Threads
1,223,896
Messages
6,175,265
Members
452,627
Latest member
KitkatToby

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top