Paper Size in Excel Addin

Paper Size in Excel Addin

Paper Size:

Paper size is refers to PaperSize property which is exposed by PageSetup object in Word object model. In this article we will see how we can change paper size grammatically as well as manually.

To change page in Excel follow the steps:

  • Click on Page Layout Ribbon tab
  • Click on Size dropdown button
  • Choose appropriate page size
  • Click on print under file menu to verify page size

Prerequisites:

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

C# Code example:

private void btnChangePagesize_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;
	//Change paper size
	oPageSetup.PaperSize = excel.XlPaperSize.xlPaperA4;
}

List of available page size in VSTO C# Excel, Note: all named constants are derived from XlPaperSize enum. I tried below list for some of the constants if you need more you can explore by putting a DOT under XlPaperSize enum:

  • xlPaperA4
  • xlPaperLegal
  • xlPaper10x14
  • xlPaper11x17
  • xlPaperA3
  • xlPaperA4Small
  • xlPaperA5
  • xlPaperB4
  • xlPaperB5
  • xlPaperCsheet
  • xlPaperDsheet
  • xlPaperEnvelope10
  • xlPaperEnvelope11

VBA code example:

Public Sub ChangePageSize()
	'get active sheet reference
	Dim oWorkSheet As Worksheet
	Set oWorkSheet = ActiveWorkbook.ActiveSheet

	'get PageSetup reference
	Dim oPageSetup As PageSetup
	Set oPageSetup = oWorkSheet.PageSetup

	'Change paper size
	oPageSetup.PaperSize = xlPaperA4
End Sub

VB.Net code example:

Private Sub Button1_Click(sender As Object, e As RibbonControlEventArgs) Handles Button1.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

        'Change paper size
        oPageSetup.PaperSize=XlPaperSize.xlPaperA4

    End Sub

Next : How to set print area in Excel Addin

Leave a Reply

Your email address will not be published.