1

I want to copy a range from a workbook and transpose it into my current sheet.

Why would I get a "Subscript out of range" error on this line:

Workbooks("Libraries\Documents\Book1.xlsx").Worksheets("Sheet1").Range("A1:A5").Copy

Sub PasteSpecial_Examples()
'https://stackoverflow.com/questions/8852717/excel-vba-range-copy-transpose-paste
'https://www.excelcampus.com/vba/copy-paste-cells-vba-macros/

    Workbooks("Libraries\Documents\Book1.xlsx").Worksheets("Sheet1").Range("A1:A5").Copy
    ActiveSheet.Range("A1").PasteSpecial Transpose:=True

End Sub
flywire
  • 1,155
  • 1
  • 14
  • 38

2 Answers2

2
  • Excel only permits one workbook open with a certain filename at the same time, even if those workbooks exist in different directories (which they must, or they couldn't have the same filename).

  • The Workbooks collection's index is just the filename, not the fully-qualified path and name.

I'm not sure whether the first point is the reason for the second point, or whether the second point is the reason for the first point, but they will be related.

So your code should be:

Sub PasteSpecial_Examples()
    Workbooks("Book1.xlsx").Worksheets("Sheet1").Range("A1:A5").Copy
    ActiveSheet.Range("A1").PasteSpecial Transpose:=True    
End Sub

Based on comments implying that you haven't yet opened Libraries\Documents\Book1.xlsx when you run your code, you could do this:

Sub PasteSpecial_Examples()
    Dim wsDst As WorkSheet
    Set wsDst = ActiveSheet        
    Workbooks.Open "Libraries\Documents\Book1.xlsx"
    Workbooks("Book1.xlsx").Worksheets("Sheet1").Range("A1:A5").Copy
    wsDst.Range("A1").PasteSpecial Transpose:=True    
End Sub

which continues to refer to the workbook by its name.

Or, slightly better, do this:

Sub PasteSpecial_Examples()
    Dim wbSrc As WorkBook
    Dim wsDst As WorkSheet
    Set wsDst = ActiveSheet        
    Set wbSrc = Workbooks.Open("Libraries\Documents\Book1.xlsx")
    wbSrc.Worksheets("Sheet1").Range("A1:A5").Copy
    wsDst.Range("A1").PasteSpecial Transpose:=True    
End Sub

which assigns a Workbook object to refer to the newly opened workbook and then uses that object in the Copy statement.

Note: In this code "Libraries\Documents\Book1.xlsx" is a relative reference to the file, e.g. if the current directory was C:\Temp then it would look for the file C:\Temp\Libraries\Documents\Book1.xlsx. You should seriously consider using an absolute reference if possible.

YowE3K
  • 23,852
  • 7
  • 26
  • 40
  • Much appreciated. How do I specify the path for the Workbook? – flywire Dec 22 '17 at 00:52
  • You don't **need** to specify the path - you can only have one workbook called "Book1.xlsx" open at any time, so Excel knows that it is the one that is open with that name. (Or are you wanting to know how to **open** a workbook???) – YowE3K Dec 22 '17 at 01:10
  • See below but you can't have multiple workbooks with the same name opened as mentioned above. It is good practice to be very explicit about what workbook and worksheet you are referring to, else you will eventually run into a problem where Excel can not resolve it for you. – Wookies-Will-Code Dec 22 '17 at 01:13
  • Now I understand - my logic is flawed. I have a sheet open and I want to copy a range from another workbook with a different filename into it. I know the filename of the other workbook. – flywire Dec 22 '17 at 01:14
  • @flywire Is the other workbook open, or do you need to open it? – YowE3K Dec 22 '17 at 01:16
  • all good, code is below, I open workbooks and copy info into my macro books all the time. It is a great thing to do. Allows you to use one workbook as an "application" often selecting a bunch of other sheets (reports) with different info in them. – Wookies-Will-Code Dec 22 '17 at 01:24
  • There are a few helpful topics below. but basically you open the workbook and immediately assign your workbook variable to the active workbook, doesn't effect the workbook with code in it as you can see those references are preset by other code. in this way you can open many workbooks and keep them straight, and close them, with screen updating off the user doesn't see the flashes of opening and closing the referenced workbooks. make sure your code works first though, or else you will get hung up in a problem with no screen updating :) So only turn it off and on once you have it tested. – Wookies-Will-Code Dec 22 '17 at 01:24
  • @YowE3K My current workbook wih the code is Workbook0. I need to open Workbook1, copy the range to current Workbook0 and close Workbook1. – flywire Dec 22 '17 at 01:36
  • 1
    Excellent!! Just added: wbSrc.Close SaveChanges:=False – flywire Dec 22 '17 at 02:05
0

I do it like this:

    Dim Finfo As String
    Dim FilterIndex As Long
    Dim Title As String
    Dim ExportFilename As Variant
    Dim CopyBook As Workbook
    Dim CopySheet As Worksheet
    Dim MnthName As String


    'Set up file filter
    Finfo = "Excel Files (*.xls*),*.xls*"
    'Set filter index to Excel Files by default in case more are added
    FilterIndex = 1
    ' set Caption for dialogue box
    Title = "Select a the DD Revenue Master file to Export to"

    'get the Forecast Filename
    ExportFilename = Application.GetOpenFilename(Finfo, FilterIndex, Title)

    'Handle file Selection
    If ExportFilename = False Then
        'No Export File was Selected
        MsgBox "No file was selected"

    Else
        'Check and see if this is a correct Export File
        Workbooks.Open (ExportFilename)
        Set CopyBook = ActiveWorkbook
        Set CopySheet = CopyBook.Worksheets(1)

        MsgBox "Valid File Selected."

        Application.CutCopyMode = False


        revenueSheet.Range("A1:BO500").Copy
        CopyBook.Worksheets(1).Activate
        CopyBook.Worksheets(1).Range("A1").PasteSpecial Paste:=xlPasteColumnWidths
        CopyBook.Worksheets(1).Range("A1").PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone, _
                    SkipBlanks:=False, Transpose:=False

         Application.CutCopyMode = False 'erase the clipboard

'close your stuff that you dont want open
End If

End Sub

Don't forget to close your workbooks when you are done. I had to trim a bunch of code because my file launches into a large case select. But often you select a workbook, open it, select some data, copy it, and paste it, close the workbook. Happens alot. Hope this helps. I believe that I found that you had to activate the newly selected workbook to perform actions on it. You can always refer to the workbook with the code in it as ThisWorkbook

To avoid confusion and since they are used in a bunch of modules I have a global variables module with the following in it but you could do this at the top of the sub if you don't have a complex project.

Option Explicit

Public thisWB As Workbook
Public functionSheet As Worksheet
Public revenueSheet As Worksheet
Public salesSheet As Worksheet
Public scratchSheet As Worksheet
Public lastRow As Double


'**********************************************************
'This sub routine will be used to intialize public variables
'**********************************************************

Private Sub SetPublicVariables()
    Set thisWB = ActiveWorkbook
    Set functionSheet = thisWB.Worksheets("Data Functions")
    Set revenueSheet = thisWB.Worksheets("DD Monthly Revenue")
    Set salesSheet = thisWB.Worksheets("Salespersons")
    Set scratchSheet = thisWB.Worksheets("ScratchSheet")

End Sub

I use this method alot . . . . . .

Oh, I call the public variable set up upon workbook open (you can find that method). In order to call a private sub you must use.

Application.Run "Global_Variables.SetPublicVariables"
'that is modulename.methodname if you want to pass arguments following
'Application.Run "modulename.methodname", arg1, arg2, etc.

Cheers, Happy coding - WWC