Jimbo99999
asked on
VB.Net - Excel Adding Worksheet Causing Error
Good Day Experts!
I have a very odd happening in my little program here. Currently I am making 3 tabs for my Excel output. I am trying to add a fourth one and it says you are outta luck...actually "invalid Index".
Here is how I am doing it:
Dim oXL As Excel.Application
Dim oWB As Excel.Workbook
Dim oSheet As Excel.Worksheet
Dim oSheet2 As Excel.Worksheet
Dim oSheet3 As Excel.Worksheet
Dim oSheet4 As Excel.Worksheet
oWB = oXL.Workbooks.Add
oSheet = oWB.ActiveSheet
oSheet.Name = "Velocity"
oSheet2 = oWB.Worksheets(2)
oSheet2.Name = "Paradox"
oSheet3 = oWB.Worksheets(3)
oSheet3.Name = "Total"
oSheet4 = oWB.Worksheets(4)
oSheet4.Name = "5 Velocity Simplified"
It has started erroring when I added the above 2 lines for oSheet4. When I comment those 2 lines it will not error!!!
Is there some limit or am I doing it wrong you think?
Thanks,
jimbo99999
I have a very odd happening in my little program here. Currently I am making 3 tabs for my Excel output. I am trying to add a fourth one and it says you are outta luck...actually "invalid Index".
Here is how I am doing it:
Dim oXL As Excel.Application
Dim oWB As Excel.Workbook
Dim oSheet As Excel.Worksheet
Dim oSheet2 As Excel.Worksheet
Dim oSheet3 As Excel.Worksheet
Dim oSheet4 As Excel.Worksheet
oWB = oXL.Workbooks.Add
oSheet = oWB.ActiveSheet
oSheet.Name = "Velocity"
oSheet2 = oWB.Worksheets(2)
oSheet2.Name = "Paradox"
oSheet3 = oWB.Worksheets(3)
oSheet3.Name = "Total"
oSheet4 = oWB.Worksheets(4)
oSheet4.Name = "5 Velocity Simplified"
It has started erroring when I added the above 2 lines for oSheet4. When I comment those 2 lines it will not error!!!
Is there some limit or am I doing it wrong you think?
Thanks,
jimbo99999
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Be careful. 3 sheets is the default, but it can be changed in Excel Options, so you cannot always count on that value. On my system, the initial count is 1.
You should check oWB.Sheets.Count first, and then act accordingly. You might need to add more than one sheet is the initial count is less than 3, or remove extra sheets if the initial count is more than 4 and you do not want more than 4 sheets in the Workbook.
You should check oWB.Sheets.Count first, and then act accordingly. You might need to add more than one sheet is the initial count is less than 3, or remove extra sheets if the initial count is more than 4 and you do not want more than 4 sheets in the Workbook.
ASKER
Thanks,
jimbo99999