To use VBA code:
Press Alt + F11 to open the Visual Basic for Applications (VBA) editor in Excel.
Click Insert > Module to add a new module.
Paste the code into the module.
Close the VBA editor.
Select the cells in which you want to apply the grid lines with hairpin lines.
Press Alt + F8 to open the "Macro" dialog box.
Select "AddHairpinGridLines" from the list of macros and click "Run."
This code will add hairpin grid lines (top and bottom borders) to the selected cells. Keep in mind
that this is a simple example, and you can modify the code to suit your specific needs, such as
adjusting the border styles, colors, and thicknesses.
Add to Notebook
Regenerate
1) create an Excel VBA code for creating grid lines with hairpin lines horizontally and normal lines
vertically in selected cells
Sub AddGridLinesWithHairpin()
Dim selectedRange As Range
Dim cell As Range
' Check if any cells are selected
If Selection.Cells.Count = 0 Then
MsgBox "No cells selected.", vbExclamation, "Error"
Exit Sub
End If
' Set the selected range
Set selectedRange = Selection
' Loop through each cell in the selected range
For Each cell In selectedRange.Cells
' Add top border (hairpin)
With cell.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlHairline
End With
' Add bottom border (hairpin)
With cell.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlHairline
End With
' Add left border (normal)
With cell.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlThin
End With
' Add right border (normal)
With cell.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlThin
End With
Next cell
End Sub
2) create an Excel VBA code for auto fit columns and rows and aligning the contents to left and top
in selected cells
Sub AutoFitAndAlign()
Dim selectedRange As Range
Dim cell As Range
' Check if any cells are selected
If Selection.Cells.Count = 0 Then
MsgBox "No cells selected.", vbExclamation, "Error"
Exit Sub
End If
' Set the selected range
Set selectedRange = Selection
' Loop through each cell in the selected range
For Each cell In selectedRange.Cells
' Auto-fit column width
cell.EntireColumn.AutoFit
' Auto-fit row height
cell.EntireRow.AutoFit
' Align contents to left and top
cell.HorizontalAlignment = xlLeft
cell.VerticalAlignment = xlTop
Next cell
End Sub
Sub AlignCenterSelectedCells()
Dim selectedRange As Range
' Check if any cells are selected
If Selection.Cells.Count = 0 Then
MsgBox "No cells selected.", vbExclamation, "Error"
Exit Sub
End If
' Set the selected range
Set selectedRange = Selection
' Align contents to center
selectedRange.HorizontalAlignment = xlCenter
selectedRange.VerticalAlignment = xlCenter
End Sub