Excel vba paste special method fails whenever i try to paste

我怕爱的太早我们不能终老 提交于 2020-07-19 18:35:08

问题


Hi everyone I'm fairly new at vba I'm trying to capture all ctrl+v events on my sheet and paste whatever is on the clipboard to the currently selected cell. Most of the time what i want to copy is text from firefox or from notepad E.I client's name or phonenumber that is n our website however the code only works when i try to paste inside de cell itself (in cell edit mode)

    Private Sub CopyPaste()

'PasteSpecial Values Only
  ActiveCell.PasteSpecial Paste:=xlPasteValues, skipblanks:=True

this returns a runtime error 1004 pastespecial method of range class failed i have also tried this but it returns a error too

activecell.PasteSpecial Format:="Text", skipblanks:=True, link:=False, DisplayAsIcon:=False

As a note the main reason for pasting text only and values only is because my excel has a very specific cell layout with colors and other stuff and a normal paste messes everything up.

I would love it if anyone could help me out


回答1:


Range.PasteSpecial method pastes a Range that has been copied into the specified Range. So this will work for Ranges only:

ActiveCell.PasteSpecial Paste:=xlPasteValues, skipblanks:=True

Clipboard needs to be accessed directly. How to use clipboard e.g. here.

Option Explicit

Sub Init()
    Application.OnKey "^{v}", "CopyPaste"
End Sub

Public Sub CopyPaste()       
    ' MSForms.DataObject can be used when MSForms lib. is referenced
    Dim clipboard As Variant 

    Dim strContents As String

    ' http://excelmatters.com/2013/10/04/late-bound-msforms-dataobject/
    ' When no MSForms is referenced yet.
    Set clipboard = CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}") 
    clipboard.GetFromClipboard
    strContents = clipboard.GetText
    ' Parse or format strContent if needed
    ActiveCell.Value = strContents
End Sub


来源:https://stackoverflow.com/questions/53232867/excel-vba-paste-special-method-fails-whenever-i-try-to-paste

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