Ottieni testo dagli Appunti utilizzando GetText - Evita Errore su Appunti vuoti
-
14-11-2019 - |
Domanda
Sto usando il codice come questo per ottenere il testo da off dagli appunti.
Dim DataObj As New MSForms.DataObject
DataObj.GetFromClipboard
myString = DataObj.GetText
.
Io uso Gestione degli errori per ottenere l'ultimo caso in cui gli Appunti sono vuoti, e tutto va bene finché continuo a tenere il trapping degli errori impostato per interrompere gli errori non gestiti.
Tuttavia, per motivi non correlati Voglio impostare l'interruttore degli errori per interrompere tutti gli errori e questo genera un errore a DataObj.GetText
quando trova gli Appunti vuoti.C'è qualche tipo di test che posso applicare ulteriormente a monte per evitare di provare a elaborare un appuntamento vuoto?
Soluzione
Does this help?
Sub GetClipBoardText()
Dim DataObj As MSForms.DataObject
Set DataObj = New MsForms.DataObject '<~~ Amended as per jp's suggestion
On Error GoTo Whoa
'~~> Get data from the clipboard.
DataObj.GetFromClipboard
'~~> Get clipboard contents
myString = DataObj.GetText(1)
MsgBox myString
Exit Sub
Whoa:
If Err <> 0 Then MsgBox "Data on clipboard is not text or is empty"
End Sub
You will notice that it will handle an empty clipboard as well.
You can empty the clipboard before testing the above code by using the code below. Please paste it in a module.
Private Declare Function OpenClipboard Lib "User32.dll" _
(ByVal hWndNewOwner As Long) As Long
Private Declare Function EmptyClipboard Lib "User32.dll" () As Long
Private Declare Function CloseClipboard Lib "User32.dll" () As Long
Public Sub ClearClipboard()
Dim Ret
Ret = OpenClipboard(0&)
If Ret <> 0 Then Ret = EmptyClipboard
CloseClipboard
End Sub
EDIT: New Request by OP
Private Declare Function CountClipboardFormats Lib "user32" () As Long
Sub Sample()
If (CountClipboardFormats() = 0) = True Then
MsgBox "Clipboard is empty"
Else
MsgBox "Clipboard is not empty"
End If
End Sub
Altri suggerimenti
Hope this helps someone else:
I was getting the error "User-Defined type not defined" on the code posted by siddharth-rout
Turns out the “Microsoft Forms 2.0 Object Library” library was missing/not activated.
Got it to work with this (http://excel-macro.tutorialhorizon.com/vba-excel-reference-libraries-in-excel-workbook/):
"Sometimes you won’t find the desired references in the list, say you won’t find “Microsoft Forms 2.0 Object Library” in the tool/reference list in that case you need to browse the FM20.DLL file from the system32"
add the follwoing code just b4 the breaking line for debuging.... the error disapeared for me after that test.. wierd but it somehow works (Excel 2010)
myString = DataObj.GetText(1)
MsgBox myString