I need to specify number of worksheets to be created using late binding. Here is my code & exception says invalid index:
oSheets = oWB.GetType()
.InvokeMember("Worksheets", BindingFlags.GetProperty, null, oWB, new object[] { 7 });
Below code works and creating 3 worksheets,
oSheets = oWB.GetType()
.InvokeMember("Worksheets", BindingFlags.GetProperty, null, oWB, null );
Let me know what I need to do to create worksheets with a specified number.
The reason you are getting an exception is that you are invoking a property and trying to pass a parameter to it. Excel by default creates 3 worksheets which is why the second line works. If you want to add more worksheets, you need to call the
Workbook.Worksheets.Add()
method and specify the count property. You can continue to use reflection as you asked but it's much easier to write (and read back) if you use thedynamic
type:And the enumeration if needed: