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

Why are there 1,048,576 rows in Excel?
The Excel team increased the size of the grid in 2007. There are 2^20 rows and 2^14 columns for a total of 17 billion cells.
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
You're welcome. Thanks for the follow-up. :)
 
Upvote 0

Forum statistics

Threads
1,215,326
Messages
6,124,258
Members
449,149
Latest member
mwdbActuary

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