Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Add worksheet in an existing workbook

Public ExlObj As Excel.Application
Public Exlsheet As Excel.Sheets

Set ExlObj = CreateObject("excel.application")
ExlObj.Workbooks.Open ("E:\myfile")
ExlObj.Visible = True

Set Exlsheet = ExlObj.ActiveWorkbook.Worksheets.Add()

m getting the type mismatch error when m adding a sheet in an existing workbook
[352 byte] By [Darakhshan] at [2007-11-11 7:38:20]
# 1 Re: Add worksheet in an existing workbook
Exlsheet is declared as Excel.Sheets. What data type does Worksheets.Add return?
Phil Weber at 2007-11-11 17:26:45 >
# 2 Re: Add worksheet in an existing workbook
First of all, you're mixing methods.

Use Early Binding to improve the speed of your app drastically:

First, in VB, set a reference to the Excel Object library. This done, you don't need the call to CreateObject.

Then try this code:

Public ExlObj As Excel.Application
Public Exlsheet As Excel.Worksheet

Set ExlObj = New Excel.Application
ExlObj.Visible = True
ExlObj.Workbooks.Open ("c:\myfile")

Set Exlsheet = Sheets.Add(After:=Worksheets(Worksheets.Count))

' You could save the file with:
ExlObj.ActiveWorkbook.Save

'And DON'T forget this line when you're all done:
ExlObj.Quit 'closes Excel completely

That will do what you want.

-Andrew
Andrew Cushen at 2007-11-11 17:27:45 >