Home » excel » excel – VBA Troubles with removing .select from code

excel – VBA Troubles with removing .select from code

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have been trying to remove the .Select from my code because I found out recently it’s not really an efficient way to do things, but i can’t get this piece of code to work.

The data I am pasting comes from another program so it is on the clipboard

My current code(which works):

Range("A3:A3").Select
        ActiveSheet.PasteSpecial Format:="Text", Link:=False, DisplayAsIcon:= _
        False

I have been trying to fix it in two ways, but both give errors.
Option 1:

Worksheets("Orders").Range("A3").PasteSpecial _
Format:="Text", Link:=False, DisplayasIcon:=False

Option 2:

Dim ws As Worksheet

Set ps = Sheets("Orders")

With ps.Range("A3")
    .PasteSpecial Format:="Text", Link:=False, DisplayAsIcon:= _
   False
End With

Both give “application defined or object defined error” so I’m doing something wrong, i just can’t figure out where the wrong part is.

How to&Answers:

Try like this

Dim Ws As Worksheet
Set Ws = Sheets("Orders")
Ws.Range("A3").PasteSpecial xlPasteAll

Answer:

Updated based on comments

As you are pasting from the clipboard directly, not from another range, you will need the Worksheet.PasteSpecial version, rather than Range.PasteSpecial.

Sub PasteFromClipboard() 
    '
    'code which loads clipboard
    '
    With Worksheets("Orders")
        .Activate 'activate the worksheet so that you can select a range on this sheet
        .Range("A3").Select        
        .PasteSpecial Format:="Text", Link:=False, DisplayasIcon:=False 
    End With   
End Sub

Answer:

For the first option you forgot the “”

This should work:

Worksheets("Orders").Range("A3").PasteSpecial _
Format:="Text", Link:=False, DisplayasIcon:=False

For the second option change ps in ws as JC Guidicelli said.

Answer:

try to declare your workbook :

Dim wb As Workbook
Set wb = ThisWorkbook

and after your worksheet :

Dim ws As Worksheet
Set ws = wb.Sheets("Orders")

and past :

ws.Range("a3").PasteSpecial xlValues