How can I avoid this exception when copying a selected range in excel?

In another question, I asked how to export an Excel spreadsheet as an image . Well, the logic of the answer is OK. But I get an exception when calling CopyPicture (System.Runtime.InteropServices.COMException).

var a = new Microsoft.Office.Interop.Excel.Application();
Workbook w = a.Workbooks.Open(@"C:\scratch\blueyellow.xlsx");
Worksheet ws = w.Sheets["StatusR"];
ws.Protect(Contents: false);

Thread.Sleep(3000); // Fix (sometimes)
Range r = ws.Range["B4:P24"];
r.CopyPicture(XlPictureAppearance.xlScreen, XlCopyPictureFormat.xlBitmap); // <--- Exception
var data = Clipboard.GetDataObject();
data.GetDataPresent(DataFormats.Bitmap);
Image image = (Image)data.GetData(DataFormats.Bitmap, true);
image.Save(@"C:\scratch\informe_by.png", System.Drawing.Imaging.ImageFormat.Png);
w.Close(SaveChanges: false);
a.Quit(); 

I set the Thread.Sleep () line before solving this problem. He works most of the time. But I would like him to always work without emergency behavior.

I am using Windows 8 Profesional 64 bit, 64 bit versions of Office 2013 and .Net 4

What could be wrong?

+1
source share
1 answer

After unsuccessful studies, I ended up in this inelegant decision:

var errorCounter = 0;
var copyDone = false;
do {
   try {
      r.CopyPicture(XlPictureAppearance.xlScreen, XlCopyPictureFormat.xlBitmap);
      copyDone = true;
   } catch {
      ++errorCounter;
} while (!copyDone && errorCounter <= 100);

if (errorCounter == 100) throw new ApplicationException("Unable to copy the selected range.");

I hope this helps others.

+1
source

All Articles