View Single Post
  #3   Report Post  
Posted to microsoft.public.excel.programming
Mike Mike is offline
external usenet poster
 
Posts: 3,101
Default Copying a worksheet from a different file into existing (VB-6/

Thank you very much. It works great in VB-6 but bombs in C#:

private void button1_Click(object sender, System.EventArgs e)
{
Excel.Workbook Wb1 = null;
Excel.Workbook Wb2 = null;
Excel.Worksheet Ws1 = null;

Excel.Application App1 = null;
Excel.Application App2 = null;

try
{

//App1 = new Excel.Application();
//App2 = new Excel.Application();

Type t1 = Type.GetTypeFromProgID("Excel.Application");
App1 = (Excel.Application) Activator.CreateInstance(t1);

Type t2 = Type.GetTypeFromProgID("Excel.Application");
App2 = (Excel.Application) Activator.CreateInstance(t2);


App1.ScreenUpdating = false;

Wb1 = App1.Workbooks.Open(@"C:\Documents and
Settings\conmxz\Desktop\EXCEL_MERGE\test1.xls",
0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
true, false, 0, true, false, false);

Wb1 = App1.ActiveWorkbook;

Wb2 = App2.Workbooks.Open(@"C:\Documents and
Settings\conmxz\Desktop\EXCEL_MERGE\test2.xls",
0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
true, false, 0, true, false, false);

Ws1 = (Excel.Worksheet) Wb2.Sheets.get_Item("Template");
Ws1.Copy(Type.Missing,Wb1.Sheets.get_Item(Wb1.Shee ts.Count));

}
catch(Exception ex)
{
Debug.WriteLine(ex.ToString());
MessageBox.Show(ex.Message);
}
finally
{
Wb1.Save();
App1.ScreenUpdating = true;
App1.Quit();
App1 = null;

Wb2.Close(false,Type.Missing,Type.Missing);
App2.Quit();
App2 = null;

Application.Exit();
this.Close();


}

}

What am I doing wrong ?

Thank you in advance,

"Ron de Bruin" wrote:

Hi Mike

You can save your one sheet workbook as a template
And use code like this to add the sheet in every workbook you want
Sheets.Add Type:=Application.TemplatesPatÂ*h & "\xxxxx.xlt"

Or open the workbook with the sheet you want to copy and copy the sheet to the active workbook

Sub test()
Dim Wb1 As Workbook
Dim Wb2 As Workbook
Application.ScreenUpdating = False
Set Wb1 = ActiveWorkbook
Set Wb2 = Workbooks.Open("C:\data\ron.xls")
Wb2.Sheets("Sheet1").copy _
after:=Wb1.Sheets(Wb1.Sheets.Count)
Wb2.Close False
Application.ScreenUpdating = True
End Sub


--
Regards Ron de Bruin
http://www.rondebruin.nl



"Mike" wrote in message ...
Hi! I have a spreadsheet which has one worksheet. I need to programmatically
add it to another spreadsheet. I see some samples on how to add a new sheet,
but not the existing. Everything I do comes up with some HRESULTS error.

Any idea/sample/url is greatly appreciated.

Thank you,

--Mike