Tuesday, November 28, 2006

Paste method of Worksheet class failed

I ran across this automation exception message sporadically in a project I'm working on where I'm trying to place a large string on the Clipboard and paste it into an Excel 2002 spreadsheet (object) using Interop in VB.NET 2005. It probably happened one time out of every five attempts to paste.

Previously, my code read:

'objWorksheet is an Excel.Worksheet automation object
Dim strClipboard As New System.Text.StringBuilder("<some humongous string>")
objWorksheet.Range("A1").Select()
System.Windows.Forms.Clipboard.SetDataObject(strClipboard.ToString())
objWorksheet.Paste()
objWorksheet.Range("A1").Select()


The exception occurred at the objWorksheet.Paste() line.

I found a Microsoft forum post here that suggested checking the Application.Ready flag before pasting, since Excel is a funny animal and needs to be in "edit mode" before it will accept a Paste command via automation. (Side note: Application.Ready only exists in Excel 2002 edition and later.)

My code now reads:

'objWorksheet is an Excel.Worksheet automation object
Dim strClipboard As New System.Text.StringBuilder("<some humongous string>")
objWorksheet.Range("A1").Select()
System.Windows.Forms.Clipboard.SetDataObject(strClipboard.ToString())
'The following is a workaround to fix a problem where Paste() is called before Excel is ready for editing
While Not objExcel.Ready
    System.Threading.Thread.Sleep(10)
End While
objWorksheet.Paste()
objWorksheet.Range("A1").Select()


No more problems!

2 comments:

Francois Wiid said...

Dave, you're my hero

Mark said...

I love how your blogpost from 2006 is still relevant and solved my "it happens sometimes and sometimes not"-problem. Thanks!