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

Copy a format multiple times
Select a formatted range. Double-click the Format Painter (left side of Home tab). You can paste formatting multiple times. Esc to stop

Forum statistics

Threads
1,216,101
Messages
6,128,835
Members
449,471
Latest member
lachbee

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