Excel VBA Macro: Check content (of clipboard?) before pasting

后端 未结 4 1298
误落风尘
误落风尘 2021-01-06 07:29

I\'ve had some serious issues with pasting data from various sources into Excel. Excel tends to try to be smart and does all kinds of silly formating. We need the data as te

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-06 07:56

    Have you considered making the cells in the target sheet equal to Text? When they're General, Excel does it's best-guess at what you expect to see.

    On the other hand if you really want to implement Paste Special...

    There is no "Paste" event you can catch - you have catch every place that a paste could occur.

    For example, you can capture the CTRL-V keypress if you issue the following code when the workbook starts up (Workbook_Open):

    Application.OnKey "^v", "DoMyPaste"
    

    This will call your function instead of the Excel paste function. Put something like this in a module:

    Public Sub DoMyPaste()
        If Selection.[is marked cell] Then
            Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
            :=False, Transpose:=False
        Else
            ActiveSheet.PasteSpecial Format:="Text", Link:=False, DisplayAsIcon _
            := False
        End If
    End Sub
    

    I have not tested this, this is more of a rough sketch. Do note that Selection could be more than one cell, so your "check for a marked cell" needs to check the whole range in some way.

    This is just the tip of the iceberg though. If you want to a full solution, you should check out this article, which is the OCD version of catching all Paste calls:

    http://www.jkp-ads.com/Articles/CatchPaste.asp
    

提交回复
热议问题