1

I only wrote my data to 1 Excel sheet, but I want to make a new sheet and call it "xxx" and write data in it.

Here is what I have now:

private static Microsoft.Office.Interop.Excel.ApplicationClass appExcel;
private static Workbook newWorkbook_First = null;
private static _Worksheet objsheet = null;

excel_init("C:\\Users\\me\\Desktop\\excel2.xlsx");

for (int i = 1; i < WindowsXPLijst.Count; i++)
{
    excel_setValue("B" + i, WindowsXPLijst[i]);
}

excel_close();

static void excel_init(String path)
{
    appExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();

    if (System.IO.File.Exists(path))
    {
        // then go and load this into excel
        newWorkbook_First = appExcel.Workbooks.Open(path, true, true);
        objsheet = (_Worksheet)appExcel.ActiveWorkbook.ActiveSheet;
    }
    else
    {
        try
        {
            appExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();
            appExcel.Visible = true;
            newWorkbook_First = appExcel.Workbooks.Add(1);
            objsheet = (Microsoft.Office.Interop.Excel.Worksheet)newWorkbook_First.Sheets[1];
        }
        catch (Exception e)
        {
            Console.Write("Error");
        }
        finally
        {
        }
    }

}

static void excel_setValue(string cellname, string value)
{
    objsheet.get_Range(cellname).set_Value(Type.Missing, value);
    objsheet.get_Range(cellname).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
}

I don't have that much changed yet, because I have no idea how to change this function:

static void excel_setValue(string cellname, string value, string tab)
{
     objsheet = tab // No ica what to exactly put here
}

{
    excel_setValue("B" + i, WindowsXPLijst[i], "xxx");
}
Mogsdad
  • 44,709
  • 21
  • 151
  • 275
wouter
  • 359
  • 4
  • 15

1 Answers1

2

This will create a new sheet after your last sheet:

Dim WS As Worksheet 
Set WS =Sheets.Add(After:=Sheets(Worksheets.count)) 
WS.name = "xxx"

This code is a condensed version of the code found here

Community
  • 1
  • 1
Paradox
  • 4,602
  • 12
  • 44
  • 88
  • Stupid Question: It cannot find the type or namespace Dim. How to fix this? – wouter Jun 11 '15 at 20:34
  • 2
    This answer is written in VBA, whereas you're looking for a C# answer. It would probably make sense to remove the [tag:vba] tag from the question, @wouter – FreeMan Jun 11 '15 at 20:36
  • 1
    Oops... Youre right, it suggested the VBA tag, so I added it.. haha.. not so smart. Thanks for deleting the tag. I am very sorry @Paradox – wouter Jun 11 '15 at 20:38
  • Excel.Worksheet newWorksheet; newWorksheet = (Excel.Worksheet)Globals.ThisWorkbook.Worksheets.Add(); – Paradox Jun 11 '15 at 20:40
  • the type or namespace name 'globals' could not be found @Paradox Could you help me with this? – wouter Jun 11 '15 at 20:48
  • 1
    Using my code it was just: `appExcel.Worksheets.Add();` Thanks for helping me out :) – wouter Jun 11 '15 at 21:03