2

Hello I have been trying to use the PasteSpecial paste values on another sheet but every thing I've tried I keep receiving the same error.

PasteSpecial method of Range class failed

xl.Application xlApp = Globals.ThisWorkbook.Application;
xl.Workbook wb = xlApp.ActiveWorkbook;
xl.Worksheet data = wb.Sheets["Data"];
xl.Worksheet datasheet = wb.Sheets["DataSheet"];
xl.Worksheet pivot = wb.Sheets["Pivot"];
xl.Range dataRng = data.Range["A1:C" + 
      xlApp.WorksheetFunction.CountA(data.Range["A:A"])];
xl.Range pivotRng = pivot.Range["A1"];

addPivot ap = new addPivot();
ap.DataRange = dataRng;
ap.DestRng = pivotRng;
ap.PivotSheet = pivot;
ap.createPivot("FullName","Date");

pivot.PivotTables("PivotTable1").NullString = "0";
pivot.UsedRange.Copy();   

datasheet.Range["A2:GT999"].ClearContents();  

datasheet.Range["A2"].PasteSpecial(xl.XlPasteType.xlPasteValues, 
                                   xl.XlPasteSpecialOperation.xlPasteSpecialOperationNone, 
                                   System.Type.Missing, System.Type.Missing);

datasheet.Range["2:2"].ClearContents();

I have Tried

datasheet.Range["A2"].PasteSpecial(xl.XlPasteType.xlPasteValues

datasheet.Range["A2"].PasteSpecial(xl.XlPasteType.xlPasteValues, 
                                   xl.XlPasteSpecialOperation.xlPasteSpecialOperationNone)

and what you see above.

thanks!

2
  • Is this a typo or what means this: datasheet.Range["2:2"].ClearContents(); It should be something like: datasheet.Range["A2:A2"].ClearContents(); Commented Jun 2, 2015 at 11:45
  • 1
    no that is correct, that clears the contents of the entire row 2 Commented Jun 2, 2015 at 13:06

1 Answer 1

3

Do the ClearContents before the Copy. Excel is removing your copied range (same as hitting ESC in the program) when you clear those cells out. Then you are trying to PasteSpecial but nothing is in the clipboard any longer.

//...code above

datasheet.Range["A2:GT999"].ClearContents();  

pivot.UsedRange.Copy();

datasheet.Range["A2"].PasteSpecial(xl.XlPasteType.xlPasteValues, 
                                   xl.XlPasteSpecialOperation.xlPasteSpecialOperationNone, 
                                   System.Type.Missing, System.Type.Missing);                                   
//code below...

If you are debugging this step-by-step, you would see the dashed border around the copied range disappear after the ClearContents call. Excel is a bit odd (but predictable) about when the copied range is forgotten. Editing cells anywhere in the Workbook is one sure way to make it forget.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.