Question

I have a Excel.Workbook.Worksheet object with N rows of data. I have a Excel.Range object that contains M rows from another worksheet. How do I add the Range to the end of the Worksheet ?

Was it helpful?

Solution 2

You should be able to do something like this (not tested, may need tweaked slightly):

using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            var application = new Application();

            var workbookCopyingFrom = application.Workbooks.Open("a.xlsx");
            var workbookCopyingTo = application.Workbooks.Open("b.xlsx");

            var worksheetContainingRangeIWantToCopyAcross = workbookCopyingFrom.Sheets[1] as Worksheet;

            if (worksheetContainingRangeIWantToCopyAcross != null)
            {
                var worksheetIWantToCopyToInWorkbookTwo = workbookCopyingTo.Sheets[2] as Worksheet;

                if (worksheetIWantToCopyToInWorkbookTwo != null)
                {
                    var usedRangeInWorkbookCopyingTo = worksheetIWantToCopyToInWorkbookTwo.UsedRange;

                    worksheetContainingRangeIWantToCopyAcross.UsedRange.Insert(XlInsertShiftDirection.xlShiftDown,
                                                                               usedRangeInWorkbookCopyingTo);

                    worksheetIWantToCopyToInWorkbookTwo.Rows.Clear();

                    worksheetIWantToCopyToInWorkbookTwo.Rows.Insert(
                        CopyOrigin: worksheetContainingRangeIWantToCopyAcross);
                }
            }

            workbookCopyingTo.Save();
            workbookCopyingTo.Close();

            application.Quit();

            Marshal.ReleaseComObject(application);
        }
    }
}

OTHER TIPS

Assuming you know how to open the two sheets (see JMK's answer if not!) the specific thing you want is:

Range src = ...
Range dest = sheet2.Cells(N+1,1);

src.Copy(dest);

If you don't know N in advance you can do something like

Range dest = wb2.Sheets["Sheet1"].Range("A1").End(XlDirection.xlDown).Offset(1);

Assuming that the first blank cell in column A is where the data should go. (also check that the destination sheet isn't empty or End() will go right to the bottom of the sheet)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top