Sub OutputDatasetBasedOnCode2()
Dim d As Object, lr As Long
Set d = CreateObject("Scripting.Dictionary")
Application.ScreenUpdating = False
Call ReplaceInvalidCharacters
With Sheets("Data")
'Get all codes in column E
lr = .Cells(Rows.Count, "E").End(xlUp).Row
For i = 5 To lr
d.Item(.Cells(i, "E").Value) = "Code2"
Next i
Debug.Print "==========" & vbCrLf & "Codes:"
For i = 0 To d.Count - 1
Debug.Print d.keys()(i)
Next i
Dim ws As Worksheet, j As Long
'Create sheets named after the codes
Application.DisplayAlerts = False
For i = 0 To d.Count - 1
If SheetExists(CStr(d.keys()(i))) Then
Sheets(CStr(d.keys()(i))).Delete
End If
Set ws = Sheets.Add(After:=Sheets(Sheets.Count))
ws.Name = d.keys()(i)
For j = 1 To 5
ws.Cells(1, j).Value = Choose(j, "Period", "Date", "Detail", "Amount", "Ref")
Next j
Next i
Application.DisplayAlerts = True
Dim fnd As Range, tempFnd As Range, lrForOutput As Long
'Output values
For i = 0 To d.Count - 1
Set fnd = .Range("E4:E" & lr).Find(d.keys()(i))
Set tempFnd = fnd
Do While Not fnd Is Nothing
lrForOutput = Sheets(CStr(d.keys()(i))).Cells(Rows.Count, "A").End(xlUp).Row + 1
Sheets(CStr(d.keys()(i))).Cells(lrForOutput, "A") = .Cells(fnd.Row, "B")
Sheets(CStr(d.keys()(i))).Cells(lrForOutput, "B") = .Cells(fnd.Row, "H")
Sheets(CStr(d.keys()(i))).Cells(lrForOutput, "C") = .Cells(fnd.Row, "I")
Sheets(CStr(d.keys()(i))).Cells(lrForOutput, "D") = .Cells(fnd.Row, "J")
Sheets(CStr(d.keys()(i))).Cells(lrForOutput, "E") = .Cells(fnd.Row, "L")
Set fnd = .Range("E4:E" & lr).FindNext(fnd)
If fnd.Address = tempFnd.Address Then Exit Do
Loop
Next i
Application.ScreenUpdating = True
MsgBox "Dataset for the following codes have been exported:" & vbCrLf & vbCrLf & Join(d.keys, ", ")
End With
End Sub
Function SheetExists(SheetName As String) As Boolean
SheetExists = False
For Each Sheet In Sheets
If Sheet.Name = SheetName Then
SheetExists = True
Exit Function
End If
Next Sheet
End Function
Sub ReplaceInvalidCharacters()
Dim lr As Long, i As Long
With Sheets("Data")
lr = .Cells(Rows.Count, "E").End(xlUp).Row
For i = 5 To lr
If InStr(CStr(.Cells(i, "E").Value), "\") > 0 Then .Cells(i, "E").Value = Replace(.Cells(i, "E").Value, "\", "_")
If InStr(CStr(.Cells(i, "E").Value), "/") > 0 Then .Cells(i, "E").Value = Replace(.Cells(i, "E").Value, "/", "_")
If InStr(CStr(.Cells(i, "E").Value), "*") > 0 Then .Cells(i, "E").Value = Replace(.Cells(i, "E").Value, "*", "_")
If InStr(CStr(.Cells(i, "E").Value), "?") > 0 Then .Cells(i, "E").Value = Replace(.Cells(i, "E").Value, "?", "_")
If InStr(CStr(.Cells(i, "E").Value), ":") > 0 Then .Cells(i, "E").Value = Replace(.Cells(i, "E").Value, ":", "_")
If InStr(CStr(.Cells(i, "E").Value), "[") > 0 Then .Cells(i, "E").Value = Replace(.Cells(i, "E").Value, "[", "_")
If InStr(CStr(.Cells(i, "E").Value), "]") > 0 Then .Cells(i, "E").Value = Replace(.Cells(i, "E").Value, "]", "_")
Next i
End With
End Sub