You could try with this code:
Sub macro1()
Dim myWb As Workbook, newWb As Workbook
Dim fileName As String, myText As String
Dim cn, rs, rs1, lastCol As Integer
Dim ctr As Integer, idx As Integer
Dim stateCodes() As String
Dim i As Integer, lastRow As Long
On Error GoTo lbl_err
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set myWb = ThisWorkbook
lastCol = myWb.Sheets("master").Cells(1, Columns.Count).End(xlToLeft).Column
'On Error Resume Next
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H1
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source='" & ThisWorkbook.FullName & "';" _
& "Extended Properties='Excel 12.0;HDR=Yes;IMEX=1'"
'get distinct stete codes
rs.Open "Select distinct [statecode] " _
& "FROM [master$] " _
& "order by 1 ", cn, adOpenStatic, adLockOptimistic, adCmdText
ctr = 3
Do While Not rs.EOF
ctr = ctr + 1
If ctr > 3 Then
idx = idx + 1
ReDim Preserve stateCodes(idx)
ctr = 1
End If
If ctr = 1 Then
stateCodes(idx) = rs(0)
Else
stateCodes(idx) = stateCodes(idx) & "_" & rs(0)
End If
rs.movenext
Loop
rs.Close
'copy data in new workbooks
For i = 1 To idx
Set newWb = Workbooks.Add
newWb.ActiveSheet.Cells(1, 1).Resize(, lastCol).Value = myWb.Sheets("master").Cells(1, 1).Resize(, lastCol).Value
rs.Open "Select * " _
& "FROM [master$] " _
& "WHERE STATECODE = '" & Replace(stateCodes(i), "_", "' OR STATECODE = '") & "'"
newWb.ActiveSheet.Range("a2").CopyFromRecordset rs
rs.Close
lastRow = newWb.ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
'paste format
myWb.Sheets("master").Range("1:1").Resize(lastRow).Copy
newWb.ActiveSheet.Range("1:1").Resize(lastRow).PasteSpecial Paste:=xlPasteFormats
newWb.ActiveSheet.Cells.Columns.AutoFit
newWb.SaveAs fileName:=myWb.Path & "\" & stateCodes(i) & "_MIS.xlsb", _
FileFormat:=xlExcel12
newWb.Close
Next
cn.Close
MsgBox ("Macro finished.")
lbl_exit:
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Exit Sub
lbl_err:
'Stop
'Resume Next
MsgBox ("An error occurred")
Resume lbl_exit
End Sub
Regards,
Antonio
Bookmarks