简体   繁体   中英

Excel VBA Copy/Paste Transpose

I need to copy cells from SheetA D3:D40 and paste transpose to SheetB C2:AN2.

This is the code I have:

Sub CopyPaste()
    Worksheets("Questions").Range("D3:D40").Select
    Selection.Copy
    Worksheets("Apps").Range("C2").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Transpose:=True
    Worksheets("Apps").Range("A1").Select
    Application.CutCopyMode = False
End Sub

After I execute this I get Run Time Error 1004 Select method of Range class failed

What am I doing wrong?

Copy this code:

Sub CopyPaste()
    With Worksheets("Questions")
        .Range("D3:D40").Copy
    End With
    With Worksheets("Apps")
        .Range("C2").PasteSpecial Paste:=xlPasteValues, Transpose:=True
    End With
    Application.CutCopyMode = False
End Sub

Using Variables in a Copy/Paste Values Transpose

Option Explicit

Sub CopyPasteTranspose()
    
    ' Source
    Dim sws As Worksheet: Set sws = ThisWorkbook.Worksheets("Questions")
    Dim srg As Range: Set srg = sws.Range("D3:D40")
    
    ' Destination
    Dim dws As Worksheet: Set dws = ThisWorkbook.Worksheets("Apps")
    Dim dfCell As Range: Set dfCell = dws.Range("C2")
    Dim drg As Range: Set drg = dfCell.Resize(srg.Columns.Count, srg.Rows.Count)
    
    ' Copy by Assignment (only values (most efficient))
    drg.Value = Application.Transpose(srg.Value)
    
    ' Note that the 'Selection' didn't change. It is as if nothing had happened,
    ' yet the values were written. You possibly don't need the following lines.
    
    'dws.Activate
    'dws.Range("A1").Select
    
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM