+ Reply to Thread
Results 1 to 7 of 7

VBA to Split Records For 3 set of Unique Values in column P:P as new workbook to path

Hybrid View

johnmacpro VBA to Split Records For 3... 05-07-2016, 03:45 PM
mike7952 Re: VBA to Split Records For... 05-08-2016, 11:47 AM
johnmacpro Re: VBA to Split Records For... 05-08-2016, 01:52 PM
antoka05 Re: VBA to Split Records For... 05-09-2016, 08:32 AM
johnmacpro Re: VBA to Split Records For... 05-09-2016, 02:13 PM
antoka05 Re: VBA to Split Records For... 05-10-2016, 03:35 AM
johnmacpro Re: VBA to Split Records For... 05-11-2016, 03:12 AM
  1. #1
    Forum Contributor
    Join Date
    02-28-2016
    Location
    australia
    MS-Off Ver
    2019
    Posts
    194

    VBA to Split Records For 3 set of Unique Values in column P:P as new workbook to path

    Dear experts

    I have master report which consolidated structured data i want split as three unique records depends upon state code in column P:P,copy to new workbook save file name as xlsb in target path.

    there is 11 unique records in P:P like AZ,CA,FL,NY,NJ,NM,MS,NH,TX,GA,HI i want split wb as Report - AZ_CA_FL_MIS.xlsb,Report - NY_NJ_NM_MIS.xlsb,Report - MS_NH_TX_MIS.xlsb, atlast Report - GA_HI_MIS.xlsb becz there is 2 end file only so it get split only two values.



    Please find the attachment Foxstreet is master file, rest of two file excepted result
    Attached Files Attached Files

  2. #2
    Forum Expert mike7952's Avatar
    Join Date
    12-17-2011
    Location
    Florida
    MS-Off Ver
    Excel 2007, Excel 2016
    Posts
    3,551

    Re: VBA to Split Records For 3 set of Unique Values in column P:P as new workbook to path

    One way

    Const adFilterNone As Long = 0
    Const adUseClient As Long = 3
    Const adOpenForwardOnly As Long = 0
    Const adLockReadOnly As Long = 1
    Const adCmdText As Long = 1
    Public Function RecordSetFromSheet(sheetName As String)
    
     Dim oRs As Object
     Dim oCnn As Object
     Dim oCmd As Object
    
        'setup the connection
        '[HDR=Yes] means the Field names are in the first row
        Set oCnn = CreateObject("ADODB.Connection")
        With oCnn
            .Provider = "Microsoft.ACE.OLEDB.12.0"
            .ConnectionString = "Data Source='" & ThisWorkbook.FullName & "'; " & "Extended Properties='Excel 12.0;HDR=Yes;IMEX=1'"
            .Open
        End With
    
        'setup the command
        Set oCmd = CreateObject("ADODB.Command")
        Set oCmd.ActiveConnection = oCnn
        With oCmd
            .CommandType = adCmdText
            .CommandText = "SELECT * FROM [" & sheetName & "$]"
        End With
        Set oRs = CreateObject("ADODB.Recordset")
        With oRs
            .CursorLocation = adUseClient
            .CursorType = adOpenForwardOnly
            .LockType = adLockReadOnly
            .Open oCmd
        End With
        'disconnect the recordset
        Set oRs.ActiveConnection = Nothing
    
        'cleanup
        If CBool(oCmd.State And adStateOpen) = True Then
            Set oCmd = Nothing
        End If
    
        If CBool(oCnn.State And adStateOpen) = True Then oCnn.Close
        Set oCnn = Nothing
    
        '"return" the recordset object
        Set RecordSetFromSheet = oRs
    
    End Function
    
    Public Sub Test()
     
     Dim oRsData As Object
     Dim fld, arrFields
     Dim i As Long
     
     Set oRsData = RecordSetFromSheet("Master")
     ReDim arrFields(1 To 1, 1 To oRsData.Fields.Count)
     For Each fld In oRsData.Fields
        i = i + 1
        arrFields(1, i) = fld.Name
     Next
     
     With Application
        .ScreenUpdating = False
        .DisplayAlerts = False
        .StatusBar = "Creating file: Report - AZ_CA_FL_MIS"
         With Workbooks.Add
            With oRsData
                .Filter = "[StateCode]='AZ' or [StateCode]='CA' or [StateCode]='FL'"
                With Range("A1")
                    .Resize(, UBound(arrFields, 2)) = arrFields
                    .Offset(1).CopyFromRecordset oRsData
                End With
                .Filter = adFilterNone
            End With
            .SaveAs ThisWorkbook.Path & "\Report - AZ_CA_FL_MIS", xlExcel12
            .Close
         End With
        
         .StatusBar = "Creating file: Report - GA_HI_MIS"
         With Workbooks.Add
            With oRsData
                .Filter = "[StateCode]='GA' or [StateCode]='HI'"
                With Range("A1")
                    .Resize(, UBound(arrFields, 2)) = arrFields
                    .Offset(1).CopyFromRecordset oRsData
                End With
                .Filter = adFilterNone
            End With
            .SaveAs ThisWorkbook.Path & "\Report - GA_HI_MIS", xlExcel12
            .Close
         End With
        
         .StatusBar = "Creating file: Report - NY_NJ_NM_MIS"
         With Workbooks.Add
            With oRsData
                .Filter = "[StateCode]='NY' or [StateCode]='NJ' or [StateCode]='NM'"
                With Range("A1")
                    .Resize(, UBound(arrFields, 2)) = arrFields
                    .Offset(1).CopyFromRecordset oRsData
                End With
                .Filter = adFilterNone
            End With
            .SaveAs ThisWorkbook.Path & "\Report - NY_NJ_NM_MIS", xlExcel12
            .Close
         End With
        
         .StatusBar = "Creating file: Report - MS_NH_TX_MIS"
         With Workbooks.Add
            With oRsData
                .Filter = "[StateCode]='MS' or [StateCode]='NH' or [StateCode]='TX'"
                With Range("A1")
                    .Resize(, UBound(arrFields, 2)) = arrFields
                    .Offset(1).CopyFromRecordset oRsData
                End With
                .Filter = adFilterNone
            End With
            .SaveAs ThisWorkbook.Path & "\Report - MS_NH_TX_MIS", xlExcel12
            .Close
         End With
        .DisplayAlerts = True
        .ScreenUpdating = True
        .StatusBar = False
     End With
     Set oRsData = Nothing
     MsgBox "Files Created Successful!", vbInformation
    End Sub
    Thanks,
    Mike

    If you are satisfied with the solution(s) provided, please mark your thread as Solved.
    Select Thread Tools-> Mark thread as Solved.

  3. #3
    Forum Contributor
    Join Date
    02-28-2016
    Location
    australia
    MS-Off Ver
    2019
    Posts
    194

    Re: VBA to Split Records For 3 set of Unique Values in column P:P as new workbook to path

    Thanks sir for Code I used to have state code more than 50 unique list any alternative code to avoid state code assign in filter record set manually! is there way to make it simple so as to avoid manual work?
    Last edited by johnmacpro; 05-08-2016 at 01:55 PM. Reason: reason

  4. #4
    Forum Expert
    Join Date
    11-23-2005
    Location
    Rome
    MS-Off Ver
    Ms Office 2016
    Posts
    1,628

    Re: VBA to Split Records For 3 set of Unique Values in column P:P as new workbook to path

    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

  5. #5
    Forum Contributor
    Join Date
    02-28-2016
    Location
    australia
    MS-Off Ver
    2019
    Posts
    194

    Re: VBA to Split Records For 3 set of Unique Values in column P:P as new workbook to path

    Yes sir it works till first 3 state code copy to newworkbook please check code with workbook!!
    Attached Files Attached Files
    Last edited by johnmacpro; 05-09-2016 at 02:16 PM. Reason: attachment

  6. #6
    Forum Expert
    Join Date
    11-23-2005
    Location
    Rome
    MS-Off Ver
    Ms Office 2016
    Posts
    1,628

    Re: VBA to Split Records For 3 set of Unique Values in column P:P as new workbook to path

    Please try to change this line of the code:
          newWb.SaveAs fileName:=myWb.Path & "C:\Users\Admin\Desktop\Brooke\Foxstreet\New folder" & stateCodes(i) & "_MIS.xlsb", _
             FileFormat:=xlExcel12
    with this:
          newWb.SaveAs fileName:="C:\Users\Admin\Desktop\Brooke\Foxstreet\New folder\" & stateCodes(i) & "_MIS.xlsb", _
             FileFormat:=xlExcel12
    Regards,
    Antonio

  7. #7
    Forum Contributor
    Join Date
    02-28-2016
    Location
    australia
    MS-Off Ver
    2019
    Posts
    194

    Re: VBA to Split Records For 3 set of Unique Values in column P:P as new workbook to path

    Thanks sir Amazing Great Help!! made my day easy one

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Split records into respective worksheet but different workbook
    By fluffyvampirekitten in forum Excel Programming / VBA / Macros
    Replies: 2
    Last Post: 08-01-2015, 07:06 AM
  2. [SOLVED] vba split data as per column unique values and move to exact workbook into sht(opencall)
    By breadwinner in forum Excel Programming / VBA / Macros
    Replies: 3
    Last Post: 01-23-2014, 11:29 PM
  3. [SOLVED] VBA to data Split from column values as new workbook save into folder with dashboard sheet
    By breadwinner in forum Excel Programming / VBA / Macros
    Replies: 15
    Last Post: 01-08-2014, 02:03 AM
  4. VBA to split column values as new workbook along with hidding sheets
    By breadwinner in forum Excel Programming / VBA / Macros
    Replies: 5
    Last Post: 07-16-2013, 08:16 AM
  5. Split Data Unique Value From 2 Sheet of A column and Move to 2 Sheet with Splited Values
    By breadwinner in forum Excel Programming / VBA / Macros
    Replies: 2
    Last Post: 05-21-2013, 04:21 AM
  6. Split Rows For Unique Values In A Column To Different Workbooks
    By ashishmac in forum Excel Programming / VBA / Macros
    Replies: 0
    Last Post: 01-22-2013, 02:45 PM
  7. split records into multiple workbook
    By tghihi in forum Excel Programming / VBA / Macros
    Replies: 6
    Last Post: 04-28-2011, 09:14 AM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1