這有幫助嗎?
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
你會注意到它也會處理一個空的剪貼板。
您可以在使用下面的代碼測試上述代碼之前清空剪貼板。請將其粘貼到模塊中。
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
編輯:由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
我會使用Dim DataObj As MSForms.DataObject和Set DataObj = MsForms.DataObject(單獨的行)來避免自動實例化變量。另外,一個函數最適合抓取剪貼板文本並將其返回。 – JimmyPena
很想看到一個示例:)事實上,會建議你在一篇新文章中發佈整個代碼。它不僅會幫助OP,還會幫助尋求解決方案的其他人:) –
啊,我只是編輯了你的答案,而不是:D – JimmyPena