Search code examples
excelvbaborder

Auto bordering cells


I'm trying to automatically border any filled cells from P13:S. When the macro runs, I also want it to detect clear cells and remove any borders currently in place. I'm using this at the moment:

Set CD = Workbooks("Savant").Worksheets("Client Details")

Application.ScreenUpdating = False

Dim lngLstCol As Long, lngLstRow As Long

lngLstRow = CD.UsedRange.Rows.Count
lngLstCol = CD.UsedRange.Columns.Count

For Each rngCell In Range(Range("P13:S13"), Cells(lngLstRow, lngLstCol))
    If rngCell.Value <> "" Then
        rngCell.Select
        With Selection.Borders
            .LineStyle = xlNone
        End With
    End If
Next

For Each rngCell In Range(Range("P13:S13"), Cells(lngLstRow, lngLstCol))
    If rngCell.Value > "" Then
        rngCell.Select
        With Selection.Borders
            .LineStyle = xlContinuous
            .Weight = xlThin
            .ColorIndex = xlAutomatic
        End With
    End If
Next

Application.ScreenUpdating = True

It's bordering cells as required, but it's failing to remove the borders from empty cells. Can anyone point out where I've gone wrong?

Many thanks


Solution

  • You can simplify your code a bit more by combining your logic so that you dont have to loop a second time.

    For Each rngCell In Range(Range("P13:S13"), Cells(lngLstRow, lngLstCol))
        With rngCell
            If Len(Trim(.Value2)) = 0 Then
                With .Borders
                    .LineStyle = xlNone
                End With
            Else
                With .Borders
                    .LineStyle = xlContinuous
                    .Weight = xlThin
                    .ColorIndex = xlAutomatic
                End With
            End If
        End With
    Next