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:
Dave, you're my hero
I love how your blogpost from 2006 is still relevant and solved my "it happens sometimes and sometimes not"-problem. Thanks!
Post a Comment