[Solved] Copy Range to another workbook

Jul 7, 2011 at 8:41 PM

Hi, 

 

when trying an excel range from one workbooks sheet to another (ideal would be worksheet.Copy) I get "Index  0 or negative Exception". I checked the docu and the discussions but found nothin.

Is it possible to copy from one workbook to another or do I have to enumerate the values and copy them somehow? 

 

Cheers and thanks for your support

Max

Jul 8, 2011 at 10:46 AM

I got it working not as elegant as copying the first range on the second range but it works (and is still super performant).

 

foreach (ExcelRangeBase sourceCell in sheetSource.Cells[sourceStart + ":" + sourceEnd])
                {
                    if (string.IsNullOrEmpty(sheetTarget.Cells[sourceCell.Address].Formula))
                    {
                        sheetTarget.Cells[sourceCell.Address].Value = sourceCell.Value;
                    }
                    else
                    {
                        sheetTarget.Cells[sourceCell.Address].Formula = sourceCell.Formula;
                    }
                }
Dec 3, 2014 at 1:48 PM
Edited Dec 3, 2014 at 1:49 PM
Thanks Max,

I have a question, if I wanted to change the "sourceCell.Address" to begin writing from another position, for example A30, and follow the flow like your code. You know how could I? please :)

regards
Dec 3, 2014 at 2:23 PM
Wow, this post is over 3 years old :)

The following goes over every cell in between A30 and Z30 - is it that what you meant?
sourceCell.Address comes from the range iteration / foreach.

foreach (ExcelRangeBase sourceCell in sheetSource.Cells["A30" + ":" + "Z30"])
            {
                if (string.IsNullOrEmpty(sheetTarget.Cells[sourceCell.Address].Formula))
                {
                    sheetTarget.Cells[sourceCell.Address].Value = sourceCell.Value;
                }
                else
                {
                    sheetTarget.Cells[sourceCell.Address].Formula = sourceCell.Formula;
                }
            }
Dec 3, 2014 at 4:05 PM
Edited Dec 3, 2014 at 4:05 PM
Thanks Max,

But my problem is with the target excel, i think that "foreach (ExcelRangeBase sourceCell in sheetSource.Cells["A30" + ":" + "Z30"])" is for select range from the source, so i need help please for the target . This is beacuse i need add more rows to the excel of target , i have data before.

i am sorry for my english, i am noob in english and C# ; :(

Thanks