Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Subscript out of range – Run-time error '9'

I am trying to get a the data from a column in 4 sheets and combine them together. The number of rows can change so I need to automate this to do this automatically. All of these sheets are contained in a single workbook. This workbook is open.

I am using this code to try to accomplish this but I am getting subscript out of range. I believe this tells me that I am referencing somewhere outside of my array but I can’t seem to find it. Debugging points me to the For loop but it seems okay to me? Each of the array elements is a different worksheet in my workbook. The data in each worksheet is simply a player name.

Sub CopyRange()
    Dim bottomD As Integer
    Dim ws As Worksheet
    For Each ws In Sheets(Array("Batters (OF) - Bat X", "Batters (SS) - Bat X", "Batters (3B) - Bat X", "Batters (2B) - Bat X"))
        ws.Activate
        bottomD = Range("Batters (OF) - Bat X" & Rows.Count).End(xlUp).Row
        Range("A2:D" & bottomD).Copy Sheets("Batters - Bat X").Cells(Rows.Count, "Batters (OF) - Bat X").End(xlUp).Offset(1, 0)
    Next ws
End Sub

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Copy the Same Columns From Different Worksheets

Sub CopyColumns()
    
    Dim swsNames(): swsNames = Array( _
        "Batters (OF) - Bat X", _
        "Batters (SS) - Bat X", _
        "Batters (3B) - Bat X", _
        "Batters (2B) - Bat X") ' to easier check the spelling
    
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    
    Dim dws As Worksheet: Set dws = wb.Sheets("Batters - Bat X")
    Dim dfCell As Range
    Set dfCell = dws.Cells(dws.Rows.Count, "A").End(xlUp).Offset(1)
    
    Dim sws As Worksheet, srg As Range, sLastRow As Long
    
    For Each sws In wb.Worksheets(swsNames)
        sLastRow = sws.Cells(sws.Rows.Count, "A").End(xlUp).Row
        Set srg = sws.Range("A2:D" & sLastRow)
        srg.Copy dfCell
        Set dfCell = dfCell.Offset(srg.Rows.Count)
    Next sws

    MsgBox "Columns copied.", vbInformation

End Sub
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading