How to Clear Office Clipboard with VBA

喜欢而已 提交于 2019-11-27 07:08:49

问题


How would you clear the Microsoft Office Clipboard using VBA, specifically Word VBA?

I am copying a lot of data at time into the clipboard and don't want excessive data kept in the Clipboard.


回答1:


Would a simple

Application.CutCopyMode = False

work for your situation, or is this option not viable?




回答2:


Saw this on another post, and I have tested it with Word VBA.

'Clearing the Office Clipboard

    Dim oData   As New DataObject 'object to use the clipboard

    oData.SetText text:=Empty 'Clear
    oData.PutInClipboard 'take in the clipboard to empty it

Just copy and paste into your code where ever you need to clear the Clipboard.

Another thing I noticed is that when I .Quit a program, say Excel, it keeps asking me if I want to keep the data is the Clipboard. A work around is to clear the clipboard using the above stated code. See below:

'Clearing the Office Clipboard

    Dim oData   As New DataObject 'object to use the clipboard

    oData.SetText text:=Empty 'Clear
    oData.PutInClipboard 'take in the clipboard to empty it


'You can also just remove the Alert Messages from the Excel Program while    
'the code is running
'Remove alert Messages from the Excel Program when closing
ExcelProgram.DisplayAlerts = False   

'Quiting the Excel Application
ExcelProgram.Quit

I used the above example in a VBA code to import data from an Excel File. See here




回答3:


This functionality is held within the library "Microsoft Forms 2.0 Object Library". To link to that library go to the VBA editor, then Tools, References and pick it out from the list if it's not already ticked.

You can do more funky stuff with a bunch of WinAPI calls, but I generally prefer avoiding those unless absolutely necessary.

Also, don't forget about the DisplayAlerts property, which will suppress dialog boxes - although I'm not sure if it would always produce the desired result.




回答4:


Here's a solution that worked for me. This is based on a post by by Zack Barresse on VBAexpress.com:

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 Sub ClearClipboard()
    OpenClipboard (0&)
    EmptyClipboard
    CloseClipboard
End Sub

After copying this function to your VBA project, use ClearClipboard to clear it.



来源:https://stackoverflow.com/questions/32736915/how-to-clear-office-clipboard-with-vba

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