Michaelrulaz
Michaelrulaz

Reputation: 11

Copy text from a textbox to clipboard

I am trying to copy text from a Text Box to the clipboard.

Private Sub CommandButton1_Click()
    With New MSForms.DataObject
        .SetText TextBox1.Text
        .PutInClipboard
    End With
End Sub

I get

"Run-time error '424' Object required.

Debugging causes .setText TextBox1.Text to highlight and say "MyData <Object variable or with block variable not set".

Upvotes: 1

Views: 15866

Answers (4)

Jovanny
Jovanny

Reputation: 167

I think this should surely work without any problem

With Me.TextBox1 .SelStart = 0 .SelLength = Len(.Text) .Copy End With

Upvotes: 2

Sani Sanjaya
Sani Sanjaya

Reputation: 1

This is work for me. Its will be put all text in Textbox1 to clipboard so its can be use at another application via paste command.

TextBox1.SetFocus

TextBox1.SelStart = 0

TextBox1.SelLength = Len(TextBox1.Text)

TextBox1.Copy

Upvotes: 0

Danny Holstein
Danny Holstein

Reputation: 174

I found the only thing that works is the Microsoft solution. Copy the code and paste into a new module (called "ClipBoard") and, voila, reliable clipboard functions.

Upvotes: 0

Wookies-Will-Code
Wookies-Will-Code

Reputation: 735

Have a look at this: https://stackoverflow.com/a/14226925/8716187

Dim DataObj As New MSForms.DataObject

'Put a string in the clipboard
DataObj.SetText Thisworkbook.Worksheet("Sheet1").TextBox1.Text 'name of your textbox here
DataObj.PutInClipboard

'Get a string from the clipboard
DataObj.GetFromClipboard
Debug.Print DataObj.GetText

** Tested and working, no scope problems here though as Textbox, Control Button, Worksheet Code all in the same scope - you may need to describe the location of your objects enter image description here -WWC

I tested your version, it also worked, be sure your TextBox1 is what you think it is. How is it created, if at runtime it may not the the number (name) you think it is.

This also compiles and runs without error:

Private Sub CommandButton1_Click()


    With New MSForms.DataObject

    'Put a string in the clipboard
    .SetText TextBox1.Text 'name of your textbox here
    .PutInClipboard

    'Get a string from the clipboard
    .GetFromClipboard
    Debug.Print .GetText

    End With

End Sub

Upvotes: 4

Related Questions