Добрый день!
Есть парсер, который вызывается n-ное кол-во раз из другой фунции:
Dim oIE As Object
Dim oSheet As Excel.Worksheet
Dim jjj As DataObject
Dim wb As Workbook
Set wb = Workbooks(«fs_pars.xlsm»)
Set jjj = New DataObject
Set oIE = CreateObject(«internetexplorer.application»)
oIE.Navigate «с:temp» & page_s & «index.html»
Do While (oIE.ReadyState <> 4)
Loop
oIE.Visible = 0
jjj.SetText oIE.document.Body.innertext
jjj.PutInClipboard
Application.DisplayAlerts = False
Set oSheet = wb.Worksheets.add()
oSheet.Name = «Temp»
wb.Worksheets(«Temp»).Activate
wb.Worksheets(«Temp»).Cells.NumberFormat = «@»
wb.Worksheets(«Temp»).Cells(1, 1).Select
wb.Worksheets(«Temp»).Paste
Set jjj = Nothing
oIE.Quit
Set oIE = Nothing
If page_s = «» Then page_s = «1»
End Sub
Он работает, но переодически выдаёт ошибку на строчке jjj.PutInClipboard:
Run-time error ‘-2147221040(800401d0)’:
DataObject:PutInClipboard Ошибка при вызове OpenClipboard
Подскажите в чём ошибка пожалуйста!
Hi All,
I am posting this problem upon reviewing many forums with regard to this issue with no avail, hence decided to post a question with expectation to hear from an expert in this field. The issue I’m facing is listed below.
I have developed an Excel 2007 application containing VBA Macros to perform an automation. The automated workbook reads many data files in order to extract data out of them (for instance 20 files). The extracted data is run over a series of calculations
which result in populating sheets of structured data and a number of charts. Upon the end of the process the workbook prints several PDF outputs (i.e. using Excels PDF addin) and completes a single run.
The problem arises at the below code segment when I run the workbook two or more times, where at the PDF print stage it gives me a run time error saying «Run-Time Error: Document not saved. The document must be open, or an error may have been encountered
when saving». However none of the PDFs generated at the first run are never opened.
RMV_ReportsWS.ExportAsFixedFormat Type:=xlTypePDF, fileName:=filePathAndName, Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
Upon stopping the debugger and trying to manually copy any text in the VB Editor window throws an «Out Of Memory» warning message and when I try to copy any data from any of the worksheets in the workbook it throws a «Cannot Open Clipboard» warning
message. It is to note that the workbook completes fully at its first run
and subsequent runs causing the above mentioned issues.
I assume this is a matter with the clipboard however I am unable to resolve the issue. I have used the following code at each point of the code to ensure clipboard cleanup but even this does not seem to address the problem
Option Explicit Public Declare Function OpenClipboard Lib "user32" (ByVal hwnd As Long) As Long Public Declare Function EmptyClipboard Lib "user32" () As Long Public Declare Function CloseClipboard Lib "user32" () As Long Public Function ClearClipboard() If OpenClipboard(Application.hwnd) = 0 Then ClearClipboard = False Else EmptyClipboard CloseClipboard ClearClipboard = True End If End Function
As for the specs I currently run the workbook on a Windows 7 32bit, with 2GB RAM in Excel 2007 SP2.
I would really appreciate feedback from as it is a very frustrating situation.
Thank You and Best Regards,
Praneeth
Praneeth Wickramasinghe
-
#1
Hello,
I’ve been using a certain subroutine to copy and paste the values of particular cells from Excel into a different program, and until recently this has been working fantastically. But now, all of a sudden, when I try to run this sub on certain cells, I get this error: «-2147221040 (800401D0) — OpenClipboard Failed». I call the copy-and-paste sub on a lot of different cells in various macros, but for some reason the error is always thrown on the third line:
Code:
Public Sub VeryFirstPartOfOneOfMySubs(
CP ("$CB$3") 'This works fine
Sleep (100)
CP ("$BA$16") 'The error shows up here
Sleep (50)
...
End Sub
I don’t think it’s an issue of increasing the sleep time, because it’s never needed it in the past. Here’s the derivative sub («CP», short for «copy-paste»):
Code:
Private Sub CP(Rnge As String)
Dim MyData As New MSForms.DataObject
MyData.SetText Range(Rnge).Value
MyData.PutInClipboard 'The error shows up here
RC 'Short for "right-click"; simulates a right-click in another app to paste
Sleep (50)
End Sub
The only thing I can think of is that something I changed in another macro somewhere could be conflicting with normal clipboard functioning — but I don’t know why that would be. The main thing I changed was that I went from manual macro calling (clicking on the ribbon) to a visual, checkbox-and-button based interface.
Also, as another fun fact, the cells the copy-paste sub throws an error on almost always end up getting deleted (presumably by the sub itself). That’s also never happened before, and I don’t understand why an error like that would only just manifest itself now.
Thanks for any insight you might be able to provide.
Last edited: Feb 22, 2011
Which came first: VisiCalc or Lotus 1-2-3?
Dan Bricklin and Bob Frankston debuted VisiCalc in 1979 as a Visible Calculator. Lotus 1-2-3 debuted in the early 1980’s, from Mitch Kapor.
-
#2
here is a snip of code I use to copy to the clipboard, this can then be copied to anything outside of excel and inserted with control V or paste
Dim myData As DataObject
Set myData = New DataObject
myData.SetText «calendar alert added my outlook»
myData.PutInClipboard
you may need the reference to dataobject, which from memory is automatic if you start a new project and insert a userform, and then delete the project, unless of course you wish to use the form, this will load the references for Microsoft Dataobject V 2.0
-
#3
Thanks for your reply. Unfortunately, if you’ll look up in the second code block, that’s almost exactly the code I used, which is giving me problems. The «MyData.putinclipboard» command, specifically.
-
#4
Thanks for your reply. Unfortunately, if you’ll look up in the second code block, that’s almost exactly the code I used, which is giving me problems. The «MyData.putinclipboard» command, specifically.
I also have had routines that once worked fine no longer do, with a strange twist. Here’s an example:
Function RangeToText(r As Range) As String
Set MyData = New MSForms.DataObject
r.Copy
MyData.GetFromClipboard
RangeToText = MyData.GetText
Set MyData = Nothing
End Function
The procedure stops at the red line and displays the «OpenClipboard Failed» popup. If I then press Debug and then F5 (VBA Run), it works just fine!
Until the next time, that is. Restarting Excel and/or Windows 7 does not help. I’m at wits end on this.
Thanks for any help.
-
#5
I also have had routines that once worked fine no longer do, with a strange twist. Here’s an example:
Function RangeToText(r As Range) As String
Set MyData = New MSForms.DataObject
r.Copy
MyData.GetFromClipboard
RangeToText = MyData.GetText
Set MyData = Nothing
End FunctionThe procedure stops at the red line and displays the «OpenClipboard Failed» popup. If I then press Debug and then F5 (VBA Run), it works just fine!
Until the next time, that is. Restarting Excel and/or Windows 7 does not help. I’m at wits end on this.
Thanks for any help.
I’m having the same problem with similar code. Also, When pasting, I’d like to keep my default signature, not overwrite it.
Here’s the relevant snippet of my code:
Code:
Dim strPaste As Variant
Dim DataObj As MSForms.DataObject
Set DataObj = New MSForms.DataObject
DataObj.GetFromClipboard
strPaste = DataObj.GetText(1)
With OutMail
.To = Email 'extracted from excel
.BCC = "name@place.com"
.Subject = Subj 'extracted from other level of code
.BodyFormat = 2 '1=Plain text, 2=HTML 3=RichText
.Body = strPaste
.Display
End With
Please help
Last edited: Jun 24, 2014
I have a simple WPF app which creates a Thread, polls the clipboard every second and trims any strings it finds
However, in the background thread, once the string content changes, the clipboard methods fail with the exception
OpenClipboard Failed (Exception from HRESULT: 0x800401D0 (CLIPBRD_E_CANT_OPEN))
Example: I have «ABC» on my clipboard and launch the app. A messagebox will popup with the string ABC. Now I copy a string «DEF» and instead of a message box popping up, the application crashes with the above error
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Thread t = new Thread(new ThreadStart(cleanStr));
t.SetApartmentState(ApartmentState.STA);
t.Start();
}
void cleanStr()
{
string prevStr = "";
int err = 0;
while (true)
{
if (Clipboard.ContainsText() && !prevStr.Equals(Clipboard.GetText()))
{
prevStr = Clipboard.GetText();
prevStr=prevStr.Trim();
Clipboard.SetText(prevStr);
MessageBox.Show(prevStr);
Thread.Sleep(1000);
}
}
}
Код C#:
TextBox TBH2 = new TextBox();
TBH2.Text = "qqq"
Clipboard.Clear();
TBH2.SelectAll();
TBH2.Copy();
Clipboard.clear() выкидывает исключение COMExeption
ошибка при вызове OpenClipboard(Исключение из HRESULT: 0x800401D0(CLIPBRD_E_CANT_OPEN))»
Получается Clipboard занят другим процессом и удается до него достучаться.
Пробовал подождать, пока буфер не освободится, не помогает.
private void textCopyClipboard(TextBox textBox)
{
for (int i = 0; i < 100;i++)
{
try
{
Clipboard.Clear();
textBox.SelectAll();
textBox.Copy();
return;
}
catch (Exception ex)
{
System.Threading.Thread.Sleep(100);
}
}
}
Подскажите плиз, как можно побороть эту проблему.
23.09.09 00:25: Перенесено модератором из ‘.NET’ — TK
Здравствуйте, Кирилл Осенков, Вы писали:
КО>[STAThread] на точке входа стоит?
WPF по умолчанию выполняется в [STAThread].
А>WPF по умолчанию выполняется в [STAThread].
Прошу прощения, коллега, мой телепатический модуль сейчас в ремонте. Без него мне неясно, используется ли в исходном сообщении WinForms или WPF.
Кроме того можно посоветовать привести полный mixed-mode call stack для главного потока с загруженными символами. Интересно, что происходит в native code frames, может поймать native first chance exception до того, как оно HRESULT вернёт и отмотает стек.
Здравствуйте, serjik007, Вы писали:
S>ошибка при вызове OpenClipboard(Исключение из HRESULT: 0x800401D0(CLIPBRD_E_CANT_OPEN))»
S>Получается Clipboard занят другим процессом и удается до него достучаться.
S>Пробовал подождать, пока буфер не освободится, не помогает.
S>Подскажите плиз, как можно побороть эту проблему.
Код твой вставил в WPF приложение прямо в конструктор Windows1, где он и сработал без проблем. Дело не в коде. Судя по всему , у тебя что-то именно с клипбоард не то. Проверь работу ее вручную, то есть забрось туда какой-нибудь текст и убедись, что он там есть.
Если некоторое приложение вызвало OpenClipboard и не вызвало CloseClipboard, clipboard будет недоступна всем другим приложениям.
I installed Microsoft Visio 2010 Beta.
While editing a UML static structure, I selected a couple of shapes, copied, and pasted them. The copy-and-paste generated the error «OpenClipboard Failed».
After that, the properties of any shape won’t come up any more, and I can’t quit Visio (when I try to quit: «You cannot quit Visio because a program is handling an event from Visio. If VBA is at a breakpoint, reset VBA, then quit.»)
After this error occurred once, it occurred over and over again. I quit Visio throught he Task manager and started it again. But even in the newly started process, copy-and-paste wouldn’t work any more and would always result in the same error.
This makes Visio unusable for me.
Apparently, this error has been there for a while.
There is a discussion from 2004 about this bug here http://www.dotnet247.com/247reference/msgs/42/214420.aspx.
Someone called Wei-Dong Xu, Microsoft Product Support Services, said that the bug was being worked on.
This was 6 years ago, why is it still not fixed?