0

I have a macro that takes a user's input, searches an SQL Database for the information and then pastes that information into a table.

I am able to sort one column alphabetically, however the adjacent columns do not get sorted as well.

Below is a snippet of the code for sorting:

Sub testSort()
'Sheets(1).Range("A2", Sheets(1).Range("A2").End(xlDown)).Select
'Sheets(1).Range("A2:" & Sheets(1).Range("A2").End(xlDown).Address).Select
Dim testrange As Range
Set testrange = Sheets(1).Range("A2", Sheets(1).Range("A2").End(xlDown))
testrange.Sort key1:=Range("A2"), _
  order1:=xlAscending, _
  Orientation:=xlSortColumns
End Sub

Image of the original test dataset, what happens after my macro, and what it should be:
enter image description here

2
  • 2
    The range you are using for sorting, testrange, is just a single column. this means it sorts the names in column A but does not move the Numbers in column B to the name's new position. To fix this, include column B in testrange like Sheets(1).Range("A2", Sheets(1).Range("B2").End(xlDown)) Commented Oct 14, 2021 at 18:17
  • Perfect, thanks so much. Commented Oct 14, 2021 at 18:26

2 Answers 2

2

The range you are using for sorting, testrange, is just a single column. this means it sorts the names in column A but does not move the Numbers in column B to the name's new position. To fix this, include column B in testrange like

Set testrange = Sheets(1).Range("A2", Sheets(1).Range("B2").End(xlDown))

testrange now includes columns A and B.

To make this loop over multiple adjacent tables, we can use a variable for the starting position and then move the starting position for each loop.

Sub testSort()

Dim topCorner As Range
Set topCorner = Sheets(1).Range("A2")

For i = 1 To 3
    Dim testrange As Range
    Set testrange = Sheets(1).Range(topCorner, topCorner.End(xlDown).Offset(, 1))
    testrange.Sort Key1:=testrange.Columns(1), _
                   Order1:=xlAscending, _
                   Orientation:=xlSortColumns
    
    Set topCorner = topCorner.Offset(, 3)
Next
            
End Sub
Sign up to request clarification or add additional context in comments.

Comments

0

Below is the updated code that was successful

Sub testSort()

Dim testrange As Range
Set testrange = Sheets(1).Range("A2", Sheets(1).Range("B2").End(xlDown))
testrange.Sort key1:=Range("A2:B2"), _
order1:=xlAscending

End Sub

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.