View Single Post
 
Old 07-15-2017, 05:50 AM
StephenRay StephenRay is offline Windows 7 64bit Office 2010 64bit
Advanced Beginner
 
Join Date: Jan 2012
Location: Overland Park, Kansas
Posts: 53
StephenRay is on a distinguished road
Default Error with Clipboard - Getting Spaces Out of Clipboard

Hello!
I just started learning VBA.
I use a Macro to do something very simple, actually I have about ten to find different things.
But they all do the same thing:
The macro finds some text in a Word document, highlights it , then copies the selection.
So then, the clipboard is ready for me to paste it somewhere.
That is all. But it is very useful and saves me lots of time because I paste in another application as I build a document in another non Office application. I do this all day long, and my various Macros make me twice as productive.
I added some code to get the leading and trailing spaces out.
Sometimes the copied text has leading and/or trailing spaces. Sometimes there are no spaces in the copied text.
But sometimes I get an error with the clipboard. Sometimes it works great.
I cannot isolate any cause or condition as to when it might happen, or why.
It is intermittent. In addition, wouldn’t you know it, early this morning it is working perfectly.
But yesterday I was getting:
2147221040 (800401D0) - OpenClipboard Failed
Whenever the error stops the macro, the clipboard has the copied text in it, but with spaces. I know this is true because I tried a paste and the text is in there!

Here’s the Macro, below.
Sub Macro18()
' Macro18 Macro
'
'This part clears the clipboard
Dim clipboard As MSForms.DataObject
Set clipboard = New MSForms.DataObject
clipboard.SetText ""
clipboard.PutInClipboard

'This part gets a person's name from a Word document to the clipboard.
Selection.EndKey Unit:=wdStory
Selection.MoveUp Unit:=wdLine, Count:=4
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Selection.MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend
Selection.Copy

'Get the spaces out!
Dim MyDataz As DataObject
Dim strClipz As String
Set MyDataz = New DataObject

Set MyDataz = New DataObject
'The next line is highlighted in Debug as causing an error sometimes
MyDataz.GetFromClipboard
strClipz = MyDataz.GetText
strClipz = Trim(strClipz)

Set MyDataz = New DataObject

MyDataz.SetText strClipz
'The next line is highlighted in Debug as causing an error sometimes
MyDataz.PutInClipboard

End Sub
Reply With Quote