Force method (GetFromClipboard) to finish before executing next command in VBA

谁都会走 提交于 2019-12-11 19:09:12

问题


I want to copy a variable to the clipboard using the PutInClipboard-methode. Due to a known bug in Win10 I need to verify if the content of the clipboard is actually what it's suppose to be.

Unfortunalty it does not work as expected and I need to "enforce" the PutInClipboard-methode by using the wait-Methode, otherwise the comparison returns true, even though the values should not be the same:

'Put the content of a variable into the clipbaord
Dim strDesiredClipboardContent as String
Dim dataObject1 As DataObject
Set dataObject1 = New DataObject
dataObject1.SetText strDesiredClipboardContent
dataObject1.PutInClipboard

'Enforce Execution (otherwise the comparison in the end does not work)
Application.Wait Now + #12:00:01 AM#

'Get whatever is in the clipboard
Dim strActuallClipboardContent
Dim dataObject2 As MSForms.DataObject
Set dataObject2 = New MSForms.DataObject
dataObject2.GetFromClipboard    
strActuallClipboardContent = dataObject2.GetText

'Compare
If strDesiredClipboardContent <> strActuallClipboardContent Then
    MsgBox "Error"
    End If

End Sub   

I wonder if there is a different methode to enforce the complete execution of the PutInClipboard-methode then using wait()?! The goal would be to get the correct results but to ad as little "wait-time" as possible.


回答1:


You could also seperate your macro into 2 parts (e.g.: Macro1 and Macro2) and at the end of the first macro you would use

Application.Ontime Now + TimeSerial(0, 0, 1), "Macro2"

to execute the second part of your code after waiting 1 second.

In my experience, this is more reliable than using Wait or even DoEvents since this will make sure the VBA process completely ends for a brief second. From what I understand, this leaves priority to Excel and the OS to complete the operations that needs to be done i.e.: put string content in the clipboard.



来源:https://stackoverflow.com/questions/57856882/force-method-getfromclipboard-to-finish-before-executing-next-command-in-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!