Grid Lines in Excel VBA, VSTO (C#, VB.Net) code example

Grid Lines in Excel VBA, VSTO (C#, VB.Net) code example

Gridlines

Represent border around cells in a sheet. These grid lines can be taken off during presentation or printing the sheet. Excel offers Gridlines property underlying PageSetup object which is boolean type and takes true/false as input respectively. Let’s put some steps to toggle GridLines in Excel Sheet.

Steps to Toggle Gridlines

  • Open Excel sheet
  • Navigate to Page Layout Ribbon tab
  • Under Sheet Options group checkbox “View” is checked default underlying Gridlines label
  • Uncheck the “View” checkbox and notice the Sheet working area it turns into white board

Default

After Uncheck

Prerequisites

  • Visual Studio 2015 or above having Microsoft Office for Developer Tool installed
  • Create Excel Addin in C# code style (Visual Studio Tools for Office)
  • Create a ribbon designer and put button

VSTO C# code example

private void btnToggleGridlines_Click(object sender, RibbonControlEventArgs e)
{
	//reference active sheet
	excel.Worksheet oWorksheet = Globals.ThisAddIn.Application.ActiveSheet;            

	//get Page Setup object reference
	excel.PageSetup oPageSetup = oWorksheet.PageSetup;

	//Check if grid lines are visible
	if (oPageSetup.PrintGridlines == true)
		oPageSetup.PrintGridlines = false;
}

VB.Net code example

Private Sub GridLines_Click(sender As Object, e As RibbonControlEventArgs) Handles GridLines.Click
	'Bind worksheet object reference
	Dim oWorkSheet as excel.Worksheet
	oWorkSheet = Globals.ThisAddIn.Application.ActiveSheet

	Get pagesetup object
	Dim oPageSetup As excel.PageSetup
	oPageSetup=oWorkSheet.PageSetup

	'Check if grid lines are visible or not
	if oPageSetup.PrintGridlines=True Then
		oPageSetup.PrintGridlines=False
	End If

End Sub

VBA code example

Public Sub ShowHideGridLines()
    With ActiveSheet.PageSetup
        If .PrintGridlines = True Then
            .PrintGridlines = False
        End If
    End With
End Sub

Please leave your comments or queries under comment section also please do subscribe to out blogs to keep your self upto date.

Next>> Headings in Excel

Leave a Reply

Your email address will not be published. Required fields are marked *