Adding line break and alpha-sort to existing VBA

mikec82

Board Regular
Joined
Jan 13, 2009
Messages
225
I have a table that looks like this:

TeacherClass
Mark SmithEnglish
Mark SmithMath
David ParkScience
David ParkHistory

<tbody>
</tbody>

I currently have a VBA solution (at the bottom) that combines teachers to one row, and lists their classes in the next, separated by commas. Here is what the above example would look like:

TeacherClass
Mark SmithEnglish, Math
David ParkScience, History

<tbody>
</tbody>

This is working well, but there are two things I would like to see if it is possible to add:

1) Rather than classes separated by commas, it would be helpful to have a line break:

TeacherClass
Mark SmithEnglish
Math
David ParkScience
History

<tbody>
</tbody>


2) Alphabetize the classes. So History would come before Science in the example above.

Any help on this would be much appreciated.


Public Sub TeacherClass()
Dim d As Object, _
k As Variant, _
rowx As Long


Dim i As Long, _
LR As Long

Dim sWS As Worksheet, _
dWS As Worksheet

Set d = CreateObject("scripting.dictionary")


Set sWS = ActiveSheet
Set dWS = Sheets.Add


LR = sWS.Range("A" & Rows.Count).End(xlUp).Row


For i = 2 To LR
With sWS
If Not d.Exists(.Range("A" & i).Value) Then
'Add to list
d.Add .Range("A" & i).Value, .Range("B" & i).Value
Else
'Append
d(.Range("A" & i).Value) = d(.Range("A" & i).Value) & ", " & .Range("B" & i).Value
End If
End With
Next i


rowx = 2


dWS.Range("A1").Value = "Student"
dWS.Range("B1").Value = "Block"


For Each k In d.Keys
dWS.Range("A" & rowx).Value = k
dWS.Range("B" & rowx).Value = d(k)
rowx = rowx + 1
Next k


End Sub
 

Excel Facts

Lock one reference in a formula
Need 1 part of a formula to always point to the same range? use $ signs: $V$2:$Z$99 will always point to V2:Z99, even after copying

Forum statistics

Threads
1,215,488
Messages
6,125,092
Members
449,206
Latest member
ralemanygarcia

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top