Andrew
Andrew

Reputation: 25

Excel VBA - paste text from clipboard (error 1004)

can someone help me with this code?

Sub TEST()
Dim Val As Variant
Sheets("Sheet 3").Select
Val = Range("A2").Value
Sheets("Sheet 1").Select
Range("AY" & Val).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Sheets("Sheet 3").Select
Application.CutCopyMode = False
End Sub

I have to transfer simple number from web to excel. I need to copy number from web into a clipboard, then go to excel and run Macro. This macro should go to "sheet 3" set "Val" based on A2 value, go to sheet 1, select range in AY & "Val" and paste to this cell data (the number) from clipboard.

But when macro reach line 7 (Selection.PasteSpecial) Im getting Error:

Run-time error '1004': PasteSpecial method of Range class failed

Where I have the bug, please :)

Upvotes: 0

Views: 1384

Answers (1)

Zwenn
Zwenn

Reputation: 2267

You must use a MSForms.DataObject to interact with the clipboard:

Sub TextFromClipboard()
'This works only with text!
  Dim oData As Object

  'New MSForms.DataObject with guid and late binding
  Set oData = CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")

  'Get text from clipboard
  'to the DataObject
  oData.GetFromClipboard

  'Show text
  MsgBox oData.GetText
End Sub

To put text to clipboard you can use the following 2 methods:

oData.SetText sText
oData.PutInClipboard

Upvotes: 5

Related Questions