+ Reply to Thread
Results 1 to 18 of 18

Why do i get run-time error 9: subscript out of range error?

Hybrid View

  1. #1
    Registered User
    Join Date
    11-01-2020
    Location
    London, uk
    MS-Off Ver
    365
    Posts
    87

    Why do i get run-time error 9: subscript out of range error?

    So I've macros that work perfectly when I copy and paste it into the developer tool. But instead of doing that to each new excel sheet I open, I want to have it open in the background in the setting Macros in 'All Open Workbooks'. But I get the titled error instead. Here are the macros:

    Macro 1:
    Sub Macro1()
        '
        ' Macro1 Macro
        '
        ' Keyboard Shortcut: Ctrl+t
        '
        Columns("A:B").Select
        Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
        Columns("C:C").Select
        Selection.TextToColumns Destination:=Range("C1"), DataType:=xlDelimited, _
            TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
            Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
            :="|", FieldInfo:=Array(1, 1), TrailingMinusNumbers:=True
            
        Dim lastRow As Long
        Dim cell As Range
        Dim insertRow As Long
        Dim insertColumn As Long
        
        lastRow = Cells(Rows.Count, "C").End(xlUp).Row
        
        For Each cell In Range("C1:C" & lastRow)
            If InStr(cell.Value, "Level") > 0 Then
                insertRow = cell.Row
                insertColumn = cell.Column
                Range(Cells(insertRow, insertColumn - 1), Cells(insertRow, insertColumn - 1)).Value = 1
                Range(Cells(insertRow + 1, insertColumn - 1), Cells(insertRow + 1, insertColumn - 1)).Value = 1
            End If
        Next cell
        
        Columns("K:L").Select
        Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
        Columns("J:J").Select
        Selection.TextToColumns Destination:=Range("J1"), DataType:=xlFixedWidth, _
            OtherChar:="|", FieldInfo:=Array(Array(0, 1), Array(4, 1), Array(16, 1)), _
            TrailingMinusNumbers:=True
        Columns("J:K").Select
        Selection.Delete Shift:=xlToLeft
        Columns("K:K").Select
        Selection.TextToColumns Destination:=Range("K1"), DataType:=xlDelimited, _
            TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=False, _
            Semicolon:=False, Comma:=False, Space:=True, Other:=False, OtherChar _
            :="|", FieldInfo:=Array(1, 1), TrailingMinusNumbers:=True
        Selection.Delete Shift:=xlToLeft
        Columns("L:L").Select
        Selection.Delete Shift:=xlToLeft
    
    
        Dim r As Range, x, w, i As Long
        Set r = Columns("c").Find("Item", , , 2)
        If r Is Nothing Then Exit Sub
        w = Split(Split(Split(Application.Trim(r), "Standard")(0), ": ")(1), " ", 2)
        x = Filter([transpose(if((left(trim(d1:d10000),15)="Operation Costs")+(left(trim(d1:d10000),15)="Total Operation"),row(1:10000)))], False, 0)
        For i = 0 To UBound(x) - 1
            If (Trim$(Cells(x(i), "d")) Like "Operation Costs*") * (Trim$(Cells(x(i + 1), "d")) Like "Total Operation*") Then
                With Cells(x(i) + 5, 1).Resize(x(i + 1) - x(i) - 6, 3)
                    .Columns(1) = Cells(x(i), 3)
                    .Columns("b:c") = w
                End With
            End If
        Next
    End Sub
    Macro 2:
    Sub Autopopulate()
    
        Dim sourceSheet As Worksheet
        Dim destinationSheet As Worksheet
        Dim lastRow As Long
        Dim destRow As Long
        Dim i As Long
        Dim j As Long
        Dim sourceCell As Range
        Dim destinationCell As Range
        
        ' Set the source sheet
        Set sourceSheet = ThisWorkbook.Sheets("ticpr2420m000 Data Dump") ' Replace "ticpr2420m000 Data Dump" with the name of your source sheet
        
        ' Set the destination sheet
        Set destinationSheet = ThisWorkbook.Sheets("Routing") ' Replace "Routing" with the name of your destination sheet
        
        ' Find the last row in the source sheet
        lastRow = sourceSheet.Cells(sourceSheet.Rows.Count, 1).End(xlUp).Row
        
        ' Initialize destination row
        destRow = 2
        
        ' Loop through each row in the source sheet
        For i = 1 To lastRow
            ' Check if column A in the current row is not empty
            If Not IsEmpty(sourceSheet.Cells(i, 1).Value) Then
                ' Loop through each cell in the current row (excluding column K)
                For j = 1 To sourceSheet.Cells(i, sourceSheet.Columns.Count).End(xlToLeft).Column
                    ' Exclude column K
                    If j <> 11 Then
                        Set sourceCell = sourceSheet.Cells(i, j)
                        Set destinationCell = destinationSheet.Cells(destRow, j)
                        
                        ' Copy the value from the source cell to the destination cell
                        destinationCell.Value = sourceCell.Value
                    End If
                Next j
                
                ' Increment destination row
                destRow = destRow + 1
            End If
        Next i
        
     ' UnhideAllRows()
        
        ' Set the destination sheet
        Set destinationSheet = ThisWorkbook.Sheets("Routing") ' Replace "Routing" with the actual name of your destination sheet
        
        ' Clear any existing filters
        destinationSheet.AutoFilterMode = False
        
        ' Find the last row in the sheet
        lastRow = destinationSheet.Cells(destinationSheet.Rows.Count, 1).End(xlUp).Row
        
        ' Unhide all rows in the sheet
        destinationSheet.Rows("1:" & lastRow).Hidden = False
    
    
        ' Clear contents of column H in destination sheet
        destinationSheet.Range("H2:H" & destRow - 1).ClearContents
    
        'Routing to OP
        
        Dim ws As Worksheet
        Dim rng As Range
        Dim filterRange As Range
        Dim filterCriteria As String
    
        ' Set the worksheet
        Set ws = ThisWorkbook.Sheets("Routing")
    
        ' Determine the last row in the sheet
        lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    
        ' Set the range to be filtered (Columns A to V)
        Set rng = ws.Range("A1:V" & lastRow)
    
        ' Clear any existing filters
        ws.AutoFilterMode = False
    
        ' Set the filter range to include all columns from A to V (including the header row)
        Set filterRange = rng
    
        ' Set the filter criteria to filter values starting with a space in column F
        filterCriteria = " =*"
    
        ' Apply the filter to column F
        filterRange.AutoFilter Field:=6, Criteria1:=filterCriteria
    
        ' Component paste
        
        Dim maxRows As Long
        
        ' Set the source and destination sheets
        Set sourceSheet = ThisWorkbook.Sheets("ticpr2420m000 Data Dump") ' Change "Sheet1" to the name of your source sheet
        Set destinationSheet = ThisWorkbook.Sheets("Components") ' Change "Sheet2" to the name of your destination sheet
        
        ' Find the last row in the source sheet
        lastRow = sourceSheet.Cells(sourceSheet.Rows.Count, "A").End(xlUp).Row
        
        ' Initialize the destination row counter
        destRow = 2 ' Start pasting from row 2 in the destination sheet
        
        ' Calculate the maximum number of rows that can be copied without exceeding the destination sheet's capacity
        maxRows = destinationSheet.Rows.Count - destRow + 1
        
        ' Loop through each row in the source sheet
        For i = 1 To lastRow
            ' Check if the first two cells are empty and cell I has data
            If IsEmpty(sourceSheet.Cells(i, 1).Value) And IsEmpty(sourceSheet.Cells(i, 2).Value) And Not IsEmpty(sourceSheet.Cells(i, 9).Value) Then
                ' Copy the specified range of columns to the destination sheet
                sourceSheet.Range("C" & i & ":K" & i).Copy destinationSheet.Range("C" & destRow)
                destRow = destRow + 1 ' Increment the destination row counter
                
                ' Check if the maximum number of rows has been reached
                If destRow > (maxRows + 1) Then
                    Exit For
                End If
            End If
        Next i
        
        ' Clear content below the last pasted row in the destination sheet
        destinationSheet.Range("C" & destRow & ":K" & destinationSheet.Rows.Count).ClearContents
        
        ' Autofit columns in the destination sheet
        destinationSheet.UsedRange.Columns.AutoFit
        
        ' Notify user that the operation is complete
        MsgBox "Rows copied successfully!", vbInformation
    
    
        '  Copycomptobom
        
        ' Set the source sheet
        Set sourceSheet = ThisWorkbook.Sheets("Components") ' Replace "Components" with the actual name of the source sheet
        
        ' Set the destination sheet
        Set destinationSheet = ThisWorkbook.Sheets("BOM") ' Replace "BOM" with the actual name of the destination sheet
        
        ' Copy data from source sheet to destination sheet
        sourceSheet.Range("C2:K12").Copy
        destinationSheet.Range("C5").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
        
        ' Clear clipboard
        Application.CutCopyMode = False
    End Sub
    Thanks!
    Last edited by 6StringJazzer; 06-12-2023 at 01:36 PM.

  2. #2
    Administrator 6StringJazzer's Avatar
    Join Date
    01-27-2010
    Location
    Tysons Corner, VA, USA
    MS-Off Ver
    MS 365 Family 64-bit 2502
    Posts
    26,977

    Re: Why do i get run-time error 9: subscript out of range error?

    Administrative Note:

    Welcome to the forum.

    We would very much like to help you with your query, however you need to include code tags around your code.

    Please take a moment to add the tags. Posting code between [code] [/code] tags makes your code much easier to read and copy for testing, and it also maintains VBA formatting.

    Please see Forum Rule #2 about code tags and adjust accordingly. Click on Edit to open your post, then highlight your code and click the # icon at the top of your post window. More information about these and other tags can be found here

    I have done this for you to keep things moving along.
    Jeff
    | | |會 |會 |會 |會 | |:| | |會 |會
    Read the rules
    Use code tags to [code]enclose your code![/code]

  3. #3
    Administrator 6StringJazzer's Avatar
    Join Date
    01-27-2010
    Location
    Tysons Corner, VA, USA
    MS-Off Ver
    MS 365 Family 64-bit 2502
    Posts
    26,977

    Re: Why do i get run-time error 9: subscript out of range error?

    When you are asking about a VBA error always indicate which line of code causes the error.

  4. #4
    Registered User
    Join Date
    11-01-2020
    Location
    London, uk
    MS-Off Ver
    365
    Posts
    87

    Re: Why do i get run-time error 9: subscript out of range error?

    The error isn't line related though. It is related to whether the main workbook is running the macro or the minimized workbook is running it... If I run the macro using another workbook on current workbook, I get this error

  5. #5
    Administrator 6StringJazzer's Avatar
    Join Date
    01-27-2010
    Location
    Tysons Corner, VA, USA
    MS-Off Ver
    MS 365 Family 64-bit 2502
    Posts
    26,977

    Re: Why do i get run-time error 9: subscript out of range error?

    Every error is line related. It is not possible to help you diagnose this error without knowing what line of code caused it. This error can be caused by multiple problems and I can't go through your code line-by-line to try to guess what it is.

    This error can be caused by using Worksheets() or Sheets() referring to a worksheet name that does not exist. It is possible that is what is happening in your code. But without more information it's just a guess.

  6. #6
    Registered User
    Join Date
    11-01-2020
    Location
    London, uk
    MS-Off Ver
    365
    Posts
    87

    Re: Why do i get run-time error 9: subscript out of range error?

    Here is a very small code. It is happening to this as well. I get the same error no matter which macro I use (created by chatgpt):
    Remember: it doesn't error if macro is being used on the workbook it was created on, but when another workbook tries to use it, I get the error 9: subscript out of range error

    Sub s()
    
    Dim ws As Worksheet
        Dim filterRange As Range
        Dim sourceRange As Range
        Dim destinationRange As Range
        
        ' Set the worksheet
        Set ws = ThisWorkbook.Sheets("Routing")
        
    ' Clear any existing filters
        ws.AutoFilterMode = False
    
        ' Apply the filter to column E
        ws.Range("$A$1:$W$159").AutoFilter Field:=5, Criteria1:=">=6000", Operator:=xlAnd, Criteria2:="<=6999"
    
        
    End Sub
    Thanks!

  7. #7
    Administrator 6StringJazzer's Avatar
    Join Date
    01-27-2010
    Location
    Tysons Corner, VA, USA
    MS-Off Ver
    MS 365 Family 64-bit 2502
    Posts
    26,977

    Re: Why do i get run-time error 9: subscript out of range error?

    when another workbook tries to use it
    I don't understand what you mean by this. Do you mean that code in another workbook that calls the code in this one? Or did you copy this code to a different workbook?

    This is the last guess I am going to make without knowing which line of code causes the error. The workbook containing this code must have a worksheet named "Routing". Is that true when this error occurs?

  8. #8
    Registered User
    Join Date
    11-01-2020
    Location
    London, uk
    MS-Off Ver
    365
    Posts
    87

    Re: Why do i get run-time error 9: subscript out of range error?

    Actually, Macro 1 doesn't cause this issue, macro 2 does. But Macro 2 is a compilation of like 6 macros. Here is 1 of them below;

    Sub ReferenceNonEmptyCells()
        Dim sourceSheet As Worksheet
        Dim destinationSheet As Worksheet
        Dim lastRow As Long
        Dim destRow As Long
        Dim i As Long
        Dim j As Long
        Dim sourceCell As Range
        Dim destinationCell As Range
        
        ' Set the source sheet
        Set sourceSheet = ThisWorkbook.Sheets("ticpr2420m000 Data Dump") ' Replace "ticpr2420m000 Data Dump" with the name of your source sheet
        
        ' Set the destination sheet
        Set destinationSheet = ThisWorkbook.Sheets("Routing") ' Replace "Routing" with the name of your destination sheet
        
        
        
        ' Loop through each row in the source sheet
        For i = 1 To lastRow
            ' Check if column A in the current row is not empty
            If Not IsEmpty(sourceSheet.Cells(i, 1).Value) Then
                ' Loop through each cell in the current row (excluding column K)
                For j = 1 To sourceSheet.Cells(i, sourceSheet.Columns.Count).End(xlToLeft).Column
                    ' Exclude column K
                    If j <> 11 Then
                        Set sourceCell = sourceSheet.Cells(i, j)
                        Set destinationCell = destinationSheet.Cells(destRow, j)
                        
                        ' Copy the value from the source cell to the destination cell
                        destinationCell.Value = sourceCell.Value
                    End If
                Next j
                
                ' Increment destination row
                destRow = destRow + 1
            End If
        Next i
        
    End Sub
    And yes, there is a worksheet called Routing. This works when I executive the code on the main workbook (Book 7), but when I execute it on a different workbook like this:
    ibb.co/ DrDpTnm- remove space to see the picture. It doesn't work

    I even tried removing lines of coding to check and I still keep getting the error

  9. #9
    Administrator 6StringJazzer's Avatar
    Join Date
    01-27-2010
    Location
    Tysons Corner, VA, USA
    MS-Off Ver
    MS 365 Family 64-bit 2502
    Posts
    26,977

    Re: Why do i get run-time error 9: subscript out of range error?

    Quote Originally Posted by skhande2 View Post
    when I execute it on a different workbook like this:
    ibb.co/ DrDpTnm- remove space to see the picture.
    You can upload images directly to a post, which saves steps over uploading to a third-party site then including a non-working link to it.

    runmacro.jpg

  10. #10
    Forum Guru TMS's Avatar
    Join Date
    07-15-2010
    Location
    The Great City of Manchester, NW England ;-)
    MS-Off Ver
    MSO 2007,2010,365
    Posts
    48,454

    Re: Why do i get run-time error 9: subscript out of range error?

    ThisWorkbook refers to the workbook with the code in it. Perhaps you should try using ActiveWorkbook instead.
    Trevor Shuttleworth - Retired Excel/VBA Consultant

    I dream of a better world where chickens can cross the road without having their motives questioned

    'Being unapologetic means never having to say you're sorry' John Cooper Clarke


  11. #11
    Registered User
    Join Date
    11-01-2020
    Location
    London, uk
    MS-Off Ver
    365
    Posts
    87

    Re: Why do i get run-time error 9: subscript out of range error?

    To use active workbook, I would need to copy paste the macro to the new workbook each time. I wanna have the macro in the background in another workbook so whenever I open a new workbook, I can just execute it with a shortcut.

  12. #12
    Forum Expert romperstomper's Avatar
    Join Date
    08-13-2008
    Location
    England
    MS-Off Ver
    365, varying versions/builds
    Posts
    21,998

    Re: Why do i get run-time error 9: subscript out of range error?

    Quote Originally Posted by skhande2 View Post
    To use active workbook, I would need to copy paste the macro to the new workbook each time.
    No, you would not. It will refer to whatever workbook is active when the code is running, no matter which workbook the code is in. ThisWorkbook by contrast, as Trevor said, always refers to the workbook with the code in it.
    Everyone who confuses correlation and causation ends up dead.

  13. #13
    Forum Guru
    Join Date
    04-13-2005
    Location
    North America
    MS-Off Ver
    2002/XP, 2007, 2024
    Posts
    16,437

    Re: Why do i get run-time error 9: subscript out of range error?

    There are three ways to refer to a workbook:

    1) As ThisWorkbook. As already noted, this ALWAYS refers to the workbook that contains the code. It sounds like you want the code stored in a common workbook, so that the code will never really work on the workbook that contains the code.
    2) As ActiveWorkbook. This ALWAYS refers to the currently active workbook. This does not mean that the code must be housed in the active workbook; only that the workbook must be active at the time of execution. You can use ActiveWorkbook as long as you can be confident that you and your users will have the desired workbook open when executing the code.
    3) As a named member of the Workbooks() collection. When you do not want to ALWAYS work on ThisWorkbook and cannot be certain that ActiveWorkbook will ALWAYS be the correct workbook, then you will need to use the Workbooks() collection to access the desired workbook. If you know the name of the workbook will always be the same, you can hardcode the name into the procedure. Or you can use an inputbox to have the user enter the name, or any of a number of other strategies for getting the desired workbook name so your procedure can access the desired workbook.

    Currently, your code is using ThisWorkbook, which seems like the wrong approach for what you want.

    I think many programmers would design this procedure to work on ActiveWorkbook with an error trap that traps the "wrong workbook open and active at time of execution" error with a message that the user should be sure that the correct workbook is open and active before executing the procedure and then terminating the procedure. This seems like it could easily be made to work for a "when I open a new workbook [so it should be the ActiveWorkbook], I can just execute [this procedure being stored in another workbook] with a shortcut" kind of scenario.

    If you decide that you don't want to use either ThisWorkbook or ActiveWorkbook, then you as the programmer need to figure out how you would like the procedure to know what workbook it should be working on. Then add the appropriate lines of code to the procedure.

    How would you like to proceed?
    Quote Originally Posted by shg
    Mathematics is the native language of the natural world. Just trying to become literate.

  14. #14
    Forum Guru TMS's Avatar
    Join Date
    07-15-2010
    Location
    The Great City of Manchester, NW England ;-)
    MS-Off Ver
    MSO 2007,2010,365
    Posts
    48,454

    Re: Why do i get run-time error 9: subscript out of range error?

    You can also refer to workbooks using the Workbooks Collection Index. Maybe not appropriate here but you can loop through the collection checking the workbook names.

    I think the consensus is to refer to the Active Workbook, that is, the workbook that is selected and which you are working on, or wish to operate on. ThisWorkbook would be the "library" for the code and sitting in the background. This would need to be opened first so that the code is available for other workbooks.

  15. #15
    Registered User
    Join Date
    11-01-2020
    Location
    London, uk
    MS-Off Ver
    365
    Posts
    87

    Re: Why do i get run-time error 9: subscript out of range error?

    I'm already using - 'All Open Workbooks' Attachment 833233 This approach worked for me for Macro 1 in original post. But it doesn't work with macro in post #8.

  16. #16
    Forum Guru TMS's Avatar
    Join Date
    07-15-2010
    Location
    The Great City of Manchester, NW England ;-)
    MS-Off Ver
    MSO 2007,2010,365
    Posts
    48,454

    Re: Why do i get run-time error 9: subscript out of range error?

    Might have missed something but I don't think we've seen an example workbook where this works and one where it doesn't. Difficult to come up with constructive suggestions without the context.


    Fast answers need visual help. Please read the yellow banner at the top of this page on how to attach a file and a mocked up solution.

  17. #17
    Registered User
    Join Date
    11-01-2020
    Location
    London, uk
    MS-Off Ver
    365
    Posts
    87

    Re: Why do i get run-time error 9: subscript out of range error?

    But I already gave you the macro, open an excel sheet, save the macro as ''All Open Workbook". Then open another, make sure it has same sheet names and try and see if it will execute. You will find macro 1 in original post will and macro in post #8 won't unfortunately

  18. #18
    Forum Expert romperstomper's Avatar
    Join Date
    08-13-2008
    Location
    England
    MS-Off Ver
    365, varying versions/builds
    Posts
    21,998

    Re: Why do i get run-time error 9: subscript out of range error?

    You cannot "save a macro as all open workbooks". A macro exists in one workbook (but can affect many). As written, your code will only ever work on the workbook containing the code because it refers to ThisWorkbook, not ActiveWorkbook.

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Error code "run time error 9: subscript out of range
    By iBennett93 in forum Excel Programming / VBA / Macros
    Replies: 24
    Last Post: 06-28-2021, 05:03 AM
  2. VBA script error help: Run-time error'9': Subscript out of range.
    By TrinhNgocAnh in forum Excel Programming / VBA / Macros
    Replies: 2
    Last Post: 10-20-2018, 05:34 AM
  3. [SOLVED] Help with error run-time error '9" (subscript out of Range)
    By thong127 in forum Excel General
    Replies: 7
    Last Post: 05-02-2018, 02:17 PM
  4. [SOLVED] Run Time Error 9 - Subscript out of range
    By kersplash in forum Excel Programming / VBA / Macros
    Replies: 4
    Last Post: 01-25-2018, 02:05 AM
  5. VBA Error - Run Time Error 9 - Subscript out if range
    By theskyscraper1 in forum Excel Programming / VBA / Macros
    Replies: 3
    Last Post: 07-16-2017, 09:07 PM
  6. [SOLVED] Run-time error '9': subscript out of range - error occurs on multiple computers except one
    By BrettE in forum Excel Programming / VBA / Macros
    Replies: 7
    Last Post: 02-06-2014, 11:19 PM
  7. Run time error 9 Subscript out of range
    By vijanand1279 in forum Excel Programming / VBA / Macros
    Replies: 3
    Last Post: 11-28-2012, 03:30 PM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1