Search code examples
excelvbacopy-pastetranspose

ActiveSheet.PasteSpecial works, error with Transpose:=True


I'm doing a macro that copies the selection in the currently active worksheet and pastes it in another, with transpose. I've seen questions relating to similar issues, but all seem to be much more complex, whereas this question seems simple (and baffling) to me.

The following code works (without transpose):

Sub sbCopyRangeToAnotherSheet2()
  Selection.Copy
  Sheets("snippets").Activate
  ActiveSheet.PasteSpecial 
End Sub

The following code throws a

1004 error - application-defined or object-defined error

(only change: added transpose):

Sub sbCopyRangeToAnotherSheet2()
  Selection.Copy
  Sheets("snippets").Activate
  ActiveSheet.PasteSpecial transpose:=true
End Sub

Solution

  • It does not work because the Worksheet.PasteSpecial method has no Transpose parameter. Note that there are 2 different PasteSpecial methods:

    1. Range.PasteSpecial method

      PasteSpecial(Paste, Operation, SkipBlanks, Transpose)
      
    2. Worksheet.PasteSpecial method

      PasteSpecial(Format, Link, DisplayAsIcon, IconFileName, IconIndex, IconLabel, NoHTMLFormatting)
      

    And you used the second one (which has no Transpose parameter and therefore errors).

    The correct syntax would be:

    Option Explicit
    
    Public Sub sbCopyRangeToAnotherSheet2()
        Selection.Copy
        ThisWorkbook.Sheets("snippets").Range("A1").PasteSpecial Transpose:=True
    End Sub
    

    You might benefit from reading How to avoid using Select in Excel VBA.