Click here to Skip to main content
15,914,360 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi All,

I am getting a PasteSpecial method of Range class failed" error
Please help code is below
C#
Microsoft.Office.Interop.Excel.Application ExcelObj = new Microsoft.Office.Interop.Excel.Application();
                    Microsoft.Office.Interop.Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(path, 0, true, 1, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);

                    Microsoft.Office.Interop.Excel.Sheets sheets = theWorkbook.Worksheets;
                    Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);
                    Range last = workSheet.Cells.SpecialCells(XlCellType.xlCellTypeLastCell,Type.Missing);
                    //Range wrange = workSheet.get_Range("A1",last);
                    Range r1 = ((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[1, 1]).EntireColumn;
                    r1.Insert(XlInsertShiftDirection.xlShiftToRight,XlInsertFormatOrigin.xlFormatFromLeftOrAbove);
                    Range r2 = (Microsoft.Office.Interop.Excel.Range)workSheet.Cells[1, 1];
                    r2.Select();
                    r2.FormulaR1C1 = "=LEFT(RC[1],100)";
                    r2.Select();
                    Range r3 = (Microsoft.Office.Interop.Excel.Range)workSheet.get_Range("A1","A160237");
                    r2.AutoFill(r3,XlAutoFillType.xlFillCopy);
                    r3.Copy(r3);
                    sheets.Add(Type.Missing, workSheet, 1, Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);
                    Microsoft.Office.Interop.Excel.Worksheet workSheetA = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(2);
                    Range r4 = (Microsoft.Office.Interop.Excel.Range)workSheetA.Cells[1, 1];
                    r4.Select();
                    r4.PasteSpecial(XlPasteType.xlPasteValues, XlPasteSpecialOperation.xlPasteSpecialOperationNone,false,false);

Paste special is working fine in my VBA code

VBA code is as follow

Selection.Copy
    Sheets("Sheet3").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
Posted
Updated 21-Apr-11 6:09am
v3

1 solution

This thread is on the same issue :

http://social.msdn.microsoft.com/forums/en-US/vbgeneral/thread/82e773a2-e0d4-43d1-b4ed-0112fc7c20b2/[^]

The marked answer uses VB code but you should be able to get that converted to C#.

The core idea there is to use a fixed column width of 8. For more info on why that's needed, see:

http://support.microsoft.com/kb/231090[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900