0

I am converting a Word VBA macro to C# as part of a plugin I am coding.

I researched the options for converting the With/End With VB block to C#. And I went ahead and tried to convert my VBA PageSetup settings:

With ActiveDocument.PageSetup
    .Orientation = wdOrientPortrait
    .TopMargin = InchesToPoints(0.98)
    .BottomMargin = InchesToPoints(0.98)
    .LeftMargin = InchesToPoints(0.92)
    .RightMargin = InchesToPoints(0.92)
    .Gutter = InchesToPoints(0)
    .HeaderDistance = InchesToPoints(0.49)
    .FooterDistance = InchesToPoints(0.49)
    .PageWidth = InchesToPoints(8.5)
    .PageHeight = InchesToPoints(11)
    .LayoutMode = wdLayoutModeDefault
End With

So using @JohnSkeet's answer to this question, I wrote my C# code:

var oPageSetup = new Word.PageSetup
{
    Orientation = Word.WdOrientation.wdOrientPortrait,
    TopMargin = (float)(0.98 * 72),
    BottomMargin = (float)(0.98 * 72),
    LeftMargin = (float)(0.92 * 72),
    RightMargin = (float)(0.92 * 72),
    Gutter = (float)(0),
    HeaderDistance = (float)(0.49 * 72),
    FooterDistance = (float)(0.49 * 72),
    PageWidth = (float)(8.5 * 72),
    PageHeight = (float)(11 * 72),
    LayoutMode = Word.WdLayoutMode.wdLayoutModeDefault
};

However when doing so, I get the following compiler error:

Cannot create an instance of the abstract class or interface 'Microsoft.Office.Interop.Word.PageSetup'

Can somebody advice me on what do I do wrong and how to correct my code? Thanks in advance.

Community
  • 1
  • 1
ib11
  • 2,530
  • 3
  • 22
  • 55

1 Answers1

2

With ActiveDocument.PageSetup does not create an instance of PageSetup. It uses a property of ActiveDocument named PageSetup. Because there is no object instantiation, you cannot use the object initializer syntax Jon Skeet was referring to. Instead you will have to repeat the variable name every time:

var ps = ActiveDocument.PageSetup;

ps.Orientation = Word.WdOrientation.wdOrientPortrait;
ps.TopMargin = (float)(0.98 * 72);
ps.BottomMargin = (float)(0.98 * 72);
ps.LeftMargin = (float)(0.92 * 72);
GSerg
  • 76,472
  • 17
  • 159
  • 346
  • One simple question: for clarity of the formatting of the code, would it be considered good practice to put the different properties in its code block with `{ }`? – ib11 May 02 '16 at 18:18
  • 1
    I believe there is no consensus on that. It's a matter of style and you are free to choose, just apply your choice consistently. I would personally not do it because it would, in my opinion, confuse the reader, because it would look very similar to the object initializer syntax, and could make you read the code wrong at a glance. – GSerg May 02 '16 at 18:52
  • Okay, thanks and also your specific reason for not using it, makes sense. – ib11 May 02 '16 at 19:11