Excel-vba: Pasting Image only from Clipboard + allowing for re-use later

[亡魂溺海] 提交于 2021-01-29 03:11:52

问题


I would like to do allow the user to do following in excel. This would probably be achieved using macros.

  1. User takes a screenshot, like with Snipping Tool
  2. Code checks if the clipboard contains an image or not (code only to run only when clipboard holds an image)
  3. Code will then paste the image from clipboard onto a specified area (e.g. Cell J55).
  4. At the same time, I want to give this pasted image an ID (say, imgSource1), so that the user can later re-use this image on another sheet (say, on sheet 2, call for imgSource1 and paste it in there)

I've gotten thus far: learnt how to paste something into excel at the said location. I haven't been able to find a working code for checking if the clipboard is holding an image or not. Now I need to figure out how to paste only image (how to check clipboard is holding only image before pasting). The following code doesn't seem to work for me.

Sub btn_addImg1()
If (Clipboard.GetImage() != null)
    Sheet1.Paste Destination:=Range("J55"), Link:=False
Else
    'do nothing
End If

The "If (Clipboard.GetImage()" line is red, and it's telling me it needs a ")" at "!=".

Note that saving an image on a local drive is not a feasible solution for my situation. It has to be pasted from the clipboard.

Thank you!


回答1:


I figured out some workaround, but it need testing.

Btw, you need to go Tools -> References -> Microsoft Forms 2.0 Oject Librarty to make MSForms working.

    Sub btn_addImg1()
    Dim DataObj As New MSForms.DataObject
    DataObj.GetFromClipboard
    On Error GoTo Img
        GetClipboardText = DataObj.GetText
    On Error GoTo 0
Img:
    If Err = -2147221404 Then
        Err = 0
        Sheet1.Paste Destination:=Sheet1.Range("J55"), Link:=False
    Else
        'do nothing
    End If
    End Sub


来源:https://stackoverflow.com/questions/41391193/excel-vba-pasting-image-only-from-clipboard-allowing-for-re-use-later

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