Click here to Skip to main content
15,916,945 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello:

I wrote 2 Functions that index the sheet names and the ranges. I then used the functions to loop through a sorting procedure. The sorting procedure works well if I run just one sheet, but if I try to sue on my For Loop, I get the error above.

Here is my code:

    Dim xlWB As Excel.Workbook = CType(Globals.ThisWorkbook.Application.ActiveWorkbook, Excel.Workbook)
    Dim xlWSEmployee As Excel.Worksheet = CType(CType(xlWB.Sheets("byEmployee"), Excel.Worksheet), Excel.Worksheet)
    Dim xlWSPosition As Excel.Worksheet = CType(CType(xlWB.Sheets("byPosition"), Excel.Worksheet), Excel.Worksheet)

    
Public Function SheetsToSort(Index As Long) As Excel.Worksheet

        Select Case Index

            Case 1 : Return xlWSEmployee
            Case 2 : Return xlWSPosition

        End Select

        Throw New ArgumentOutOfRangeException("Index")

    End Function

    Public Function GetRange(Index As Long) As Excel.Range

        Select Case Index

            Case 1 : Return xlWSEmployee.Range("A1")
            Case 2 : Return xlWSPosition.Range("W1")

        End Select

        Throw New ArgumentOutOfRangeException("Index")

    End Function

    Sub Sort_Sheets()


        Dim refSheets As Excel.Worksheet
        Dim sortRange As Excel.Range
        Dim sheetRange As Excel.Range
        Dim x As Long


        'This is Step 6 when the frmDataImportSplash is activated.

        'The key formulas only work if the data is sorted properly. The procedure
        'below sorts each sheet by the required field. Look at the public_Declarations module
        'for the pass byRef.

        For x = 1 To 2 Step 1

            refSheets = SheetsToSort(x)
            sortRange = GetRange(x)

            sheetRange = xlWSPosition.Range("A:W")
            sheetRange.Select()

            sheetRange.Sort(Key1:=sheetRange.Range(sortRange), _
                         Order1:=Excel.XlSortOrder.xlAscending, _
                         Orientation:=Excel.XlSortOrientation.xlSortColumns, MatchCase:=False, _
                         Header:=XlYesNoGuess.xlYes)


        Next x

    End Sub
Posted
Comments
[no name] 16-Sep-13 14:54pm    
You need to find out which COM error you are getting before you can fix it.
qbndl8 17-Sep-13 0:46am    
Thank you, I was able to figure it out

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900