How to paste directly from clipboard using VBA

SDPanda

New Member
Joined
Jan 29, 2023
Messages
7
Office Version
  1. 365
Platform
  1. Windows
Hi,

New to VBA. My goal is to automatically paste (values only) copied from an external table into cell A1 of Sheet 1 upon opening the Workbook.

I have figured out how to set the active sheet/cell and paste directly from clipboard using MS.Forms.DataObject. The problem I have is that multiple rows/columns of data are pasted into a single cell. If I try text to columns only the first row of data is shown, multiple times.

VBA Code:
Public Sub Worksheet_ActivateAndPasteSpecial()

    Sheet1.Activate
    Range("A1:ZZ1000").Select
    Range("A1").Activate
    
End Sub

Sub PasteSpecial_from_Clipboard()

Dim CObj As MSForms.DataObject
Set CObj = New MSForms.DataObject
CObj.GetFromClipboard
XText = CObj.GetText(1)
ActiveSheet.Range("A1").Value = XText

End Sub
 

Excel Facts

How to find 2nd largest value in a column?
MAX finds the largest value. =LARGE(A:A,2) will find the second largest. =SMALL(A:A,3) will find the third smallest
VBA Code:
Sub PasteValues()
    Dim DataObj As MSForms.DataObject
    Set DataObj = New MSForms.DataObject

    'Get data from clipboard
    DataObj.GetFromClipboard

    'Split the data into rows and columns
    Dim PasteData As Variant
    PasteData = DataObj.GetText(1).Split(vbCrLf)

    'Paste data into cell A1 of the active sheet
    Dim r As Long
    For r = 0 To UBound(PasteData)
        If r > 0 Then
            'Insert a new row for each row of data
            ActiveSheet.Range("A1").EntireRow.Insert
        End If
        'Paste the values into column A of the new row
        ActiveSheet.Range("A" & r + 1).Value = PasteData(r)
    Next r
End Sub
 
Upvote 1

Forum statistics

Threads
1,215,475
Messages
6,125,028
Members
449,205
Latest member
Eggy66

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top