Advertisement
Guest User

Untitled

a guest
Feb 11th, 2016
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. Name | State
  2. ---- -----
  3. Billy Utah
  4. Sue California
  5. Joe Utah
  6. Sally California
  7. John Michigan
  8.  
  9. Option Explicit
  10.  
  11. Sub CreateCSVfromWS()
  12. Dim ws As Worksheet
  13. Application.ScreenUpdating = False
  14.  
  15. Call Filter
  16. Call MakeMonthSheets
  17.  
  18. For Each ws In ActiveWorkbook.Worksheets
  19. ws.SaveAs "C:Destination" & ws.Name & ".csv", xlCSV
  20. Next
  21.  
  22. Application.ScreenUpdating = True
  23. End Sub
  24.  
  25. Sub Filter()
  26. Columns("A:B").Select
  27. Selection.AutoFilter
  28. ActiveWorkbook.Worksheets("Sheet1").AutoFilter.Sort.SortFields.Clear
  29. ActiveWorkbook.Worksheets("Sheet1").AutoFilter.Sort.SortFields.Add Key:=Range _
  30. ("B:B"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
  31. xlSortNormal
  32. With ActiveWorkbook.Worksheets("Sheet1").AutoFilter.Sort
  33. .Header = xlYes
  34. .MatchCase = False
  35. .Orientation = xlTopToBottom
  36. .SortMethod = xlPinYin
  37. .Apply
  38. End With
  39. End Sub
  40.  
  41. Sub MakeMonthSheets()
  42.  
  43. Dim rngState As Range
  44. Dim rngCell As Range
  45. Dim sh As Worksheet
  46. Dim shDest As Worksheet
  47. Dim rngNext As Range
  48.  
  49. Const sLNHEADER As String = "State"
  50.  
  51. Set sh = ThisWorkbook.Sheets("Sheet1")
  52. Set rngState = sh.UsedRange.Find(sLNHEADER, , xlValues, xlWhole)
  53.  
  54. 'Make sure you found something
  55. If Not rngState Is Nothing Then
  56. 'Go through each cell in the column
  57. For Each rngCell In Intersect(rngState.EntireColumn, sh.UsedRange).Cells
  58. 'skip the header and empty cells
  59. If Not IsEmpty(rngCell.Value) And rngCell.Address <> rngState.Address Then
  60. 'see if a sheet already exists
  61. On Error Resume Next
  62. Set shDest = sh.Parent.Sheets(rngCell.Value)
  63. On Error GoTo 0
  64.  
  65. 'if it doesn't exist, make it
  66. If shDest Is Nothing Then
  67. Set shDest = sh.Parent.Worksheets.Add
  68. shDest.Name = rngCell.Value
  69. End If
  70.  
  71. 'Find the next available row
  72. Set rngNext = shDest.Cells(shDest.Rows.Count, 1).End(xlUp).Offset(1, 0)
  73.  
  74. 'Copy and paste
  75. Intersect(rngCell.EntireRow, sh.UsedRange).Copy rngNext
  76.  
  77. 'reset the destination sheet
  78. Set shDest = Nothing
  79. End If
  80. Next rngCell
  81. End If
  82.  
  83. End Sub
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement