+ Reply to Thread
Results 1 to 22 of 22

Copy specific columns from multiple files in folder and combine those columns in workbook

Hybrid View

  1. #1
    Registered User
    Join Date
    11-14-2022
    Location
    chennai
    MS-Off Ver
    2016
    Posts
    30

    Copy specific columns from multiple files in folder and combine those columns in workbook

    Dear Gurus,
    I got the below code that it combine sheets from all the files in the folder copy to another workbook, the codes work well. But i want to copy specific columns from all the files, I tried i cannot able to get. Can you help me here please.
    I think there is no need for attachment.
    Sub MergefilesinaSheet()
    
    Dim myactiveworkbook As Workbook
    Dim mergeObj As Object, dirObj As Object, filesObj As Object, everyObj As Object
    Application.ScreenUpdating = False
    
    
    Set mergeObj = CreateObject("Scripting.FileSystemObject")
     
    'change folder path of excel files here
    Set dirObj = mergeObj.Getfolder("C:\Desktop\Merge files\")
    Set filesObj = dirObj.Files
    For Each everyObj In filesObj
    Set myactiveworkbook = Workbooks.Open(everyObj)
    
    
    Range("A1:AA" & Range("A3000").End(xlUp).Row).Copy
    ThisWorkbook.Worksheets("All Columns").Activate
     
    'Do not change the following column. It's not the same column as above
    Range("A65536").End(xlUp).Offset(1, 0).PasteSpecial Paste:=xlPasteValues
    Application.CutCopyMode = False
    myactiveworkbook.Close
    CopyColumnsByName
    
    Next
    Cells.WrapText = False
    Cells(1, 1).EntireRow.Delete
    
    End Sub
    Last edited by JaffarAhamed; 09-10-2023 at 12:04 PM. Reason: grammer mistakes

  2. #2
    Registered User
    Join Date
    11-14-2022
    Location
    chennai
    MS-Off Ver
    2016
    Posts
    30

    Re: Copy specific columns from multiple files in folder and combine those columns in workb

    below is the column header should consider from all the files in the folder
    ColumnNameList = Array("Serial No.", "Country", "Domain Owner",  "Overall Status")
    otherwise the code could be the list where i can add column headers in other sheet

  3. #3
    Forum Moderator alansidman's Avatar
    Join Date
    02-02-2010
    Location
    Steamboat Springs, CO
    MS-Off Ver
    MS Office 365 insider Version 2504 Win 11
    Posts
    24,694

    Re: Copy specific columns from multiple files in folder and combine those columns in workb

    Have you considered using Power Query? If you wish to post some sample data, with a mocked up solution, I may be able to demonstrate. Make sure to keep the number of records for each file to a minimum (8-10 records each).
    Alan עַם יִשְׂרָאֵל חַי


    Change an Ugly Report with Power Query
    Database Normalization
    Complete Guide to Power Query
    Man's Mind Stretched to New Dimensions Never Returns to Its Original Form

  4. #4
    Registered User
    Join Date
    11-14-2022
    Location
    chennai
    MS-Off Ver
    2016
    Posts
    30

    Re: Copy specific columns from multiple files in folder and combine those columns in workb

    Dear Alan, Thanks for your quick reply. I want this in VBA, but it came in the power query. Can you please assume that there are 25+ files in the folder in other path, and result should come in the sheet1 in the active workbook. If you still want sample data then i can. And every files having one sheet to combine. Thanks
    Last edited by JaffarAhamed; 09-10-2023 at 12:10 PM. Reason: grammer

  5. #5
    Administrator 6StringJazzer's Avatar
    Join Date
    01-27-2010
    Location
    Tysons Corner, VA, USA
    MS-Off Ver
    MS 365 Family 64-bit 2411
    Posts
    26,735

    Re: Copy specific columns from multiple files in folder and combine those columns in workb

    Quote Originally Posted by JaffarAhamed View Post
    I want this in VBA
    I have moved this from the Excel General subforum. If you want to change the subforum, please click Report and request a move. Do not just post a duplicate in another subforum.
    Jeff
    | | |·| |·| |·| |·| | |:| | |·| |·|
    Read the rules
    Use code tags to [code]enclose your code![/code]

  6. #6
    Registered User
    Join Date
    11-14-2022
    Location
    chennai
    MS-Off Ver
    2016
    Posts
    30

    Re: Copy specific columns from multiple files in folder and combine those columns in workb

    Hi Jazzer,
    My Apologies. I dont know how to move the post from subform. Can you help this post.

  7. #7
    Registered User
    Join Date
    11-14-2022
    Location
    chennai
    MS-Off Ver
    2016
    Posts
    30

    Re: Copy specific columns from multiple files in folder and combine those columns in workb

    I am sharing the multiple files and the file with the code.
    Basically i have files in a folders, and columns in all files are random, my code just copy the sheet and paste in to the active worksheet and so on for other files in the folder.
    But what i actually want is, copy and paste activity should follow the below column order for all files.
    Serial No.
    Country
    Domain Owner
    Other communications
    Overall status

    I have attached the file with code along with sample files.


    I hope you understand, please let me know if unclear. thanks
    Attached Files Attached Files

  8. #8
    Administrator 6StringJazzer's Avatar
    Join Date
    01-27-2010
    Location
    Tysons Corner, VA, USA
    MS-Off Ver
    MS 365 Family 64-bit 2411
    Posts
    26,735

    Re: Copy specific columns from multiple files in folder and combine those columns in workb

    Quote Originally Posted by JaffarAhamed View Post
    My Apologies. I dont know how to move the post from subform. Can you help this post.
    You cannot move a post. I moved it for you. In the future, do not duplicate a post. If you would like us to move a post, click "Report Post" under your post and request that we move it.

  9. #9
    Forum Moderator alansidman's Avatar
    Join Date
    02-02-2010
    Location
    Steamboat Springs, CO
    MS-Off Ver
    MS Office 365 insider Version 2504 Win 11
    Posts
    24,694

    Re: Copy specific columns from multiple files in folder and combine those columns in workb

    Cannot assist with VBA. If you want a PQ solution then you need to upload files as there is no such thing as a generic solution in PQ. Otherwise, good luck.

  10. #10
    Forum Guru
    Join Date
    08-15-2004
    Location
    Tokyo, Japan
    MS-Off Ver
    2013 O.365
    Posts
    22,834

    Re: Copy specific columns from multiple files in folder and combine those columns in workb

    This will not import the data from the workbook;
    1) doesn't have "owssvr" sheet.
    2) any column heading missing/doesn't match to heading in destination sheet.
    Sub test()
        Dim myDir As String, fn As String, i As Long, s
        Dim cn As Object, rs As Object
        Const wsName As String = "owssvr"
        With Application.FileDialog(msoFileDialogFolderPicker)
            If .Show Then myDir = .SelectedItems(1) & "\"
        End With
        If myDir = "" Then Exit Sub
        fn = Dir(myDir & "*.xlsx")
        Set cn = CreateObject("ADODB.Connection")
        Set rs = CreateObject("ADODB.Recordset")
        cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & myDir & fn & ";Extended Properties=""Excel 12.0;"""
        With Sheets("expected output").[a1].CurrentRegion
            .Offset(1).ClearContents
            s = .Parent.Evaluate(.Rows(1).Address & "&""""")
            Do While fn <> ""
                If IsSheetExists("'" & myDir & "[" & fn & "]" & wsName & "'", s) Then
                    rs.Open "Select `" & Replace(Join(s, "`, `"), ".", "#") & "` From " & _
                        "`Excel 12.0;DataBase=" & myDir & fn & "`.`" & wsName & "$`;", cn
                    .Range("a" & Rows.Count).End(xlUp)(2).CopyFromRecordset rs
                    rs.Close
                End If
                fn = Dir
            Loop
        End With
    End Sub
    
    Function IsSheetExists(fn, s) As Boolean
        Dim e, x
        If IsError(ExecuteExcel4Macro(fn & "!r1c1")) Then Exit Function
        For Each e In s
            x = ExecuteExcel4Macro("match(""" & e & """," & fn & "!r1:r1,0)")
            If IsError(x) Then Exit Function
        Next
        IsSheetExists = True
    End Function

  11. #11
    Registered User
    Join Date
    11-14-2022
    Location
    chennai
    MS-Off Ver
    2016
    Posts
    30

    Re: Copy specific columns from multiple files in folder and combine those columns in workb

    Hi Jindon,
    Unfortunately i got 'Mismatch error:13' for the below line
    For Each e In s

  12. #12
    Forum Guru
    Join Date
    08-15-2004
    Location
    Tokyo, Japan
    MS-Off Ver
    2013 O.365
    Posts
    22,834

    Re: Copy specific columns from multiple files in folder and combine those columns in workb

    Like I said earlier in post #9
    Quote Originally Posted by jindon View Post
    This will not import the data from the workbook;
    1) doesn't have "owssvr" sheet.
    2) any column heading missing/doesn't match to heading in destination sheet.
    Most probably other files would match to above.

    If you upload a workbook that is not imported, I can tell.

  13. #13
    Forum Guru
    Join Date
    08-15-2004
    Location
    Tokyo, Japan
    MS-Off Ver
    2013 O.365
    Posts
    22,834

    Re: Copy specific columns from multiple files in folder and combine those columns in workb

    Are you running from the file I attached?

    That error occur when you have no headings in destination sheet.
    change "test" sub to
    Sub test()
        Dim myDir As String, fn As String, i As Long, s
        Dim cn As Object, rs As Object
        Const wsName As String = "owssvr"
        With Application.FileDialog(msoFileDialogFolderPicker)
            If .Show Then myDir = .SelectedItems(1) & "\"
        End With
        If myDir = "" Then Exit Sub
        fn = Dir(myDir & "*.xlsx")
        Set cn = CreateObject("ADODB.Connection")
        Set rs = CreateObject("ADODB.Recordset")
        cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & myDir & fn & ";Extended Properties=""Excel 12.0;"""
        With Sheets("expected output")
            .[a1].CurrentRegion.ClearContents
            s = Array("Serial No.", "Country", "Overall status", "Other communications", "Domain Owner")
            .[a1].Resize(, UBound(s) + 1) = s
            Do While fn <> ""
                If IsSheetExists("'" & myDir & "[" & fn & "]" & wsName & "'", s) Then
                    rs.Open "Select `" & Replace(Join(s, "`, `"), ".", "#") & "` From " & _
                        "`Excel 12.0;DataBase=" & myDir & fn & "`.`" & wsName & "$`;", cn
                    .Range("a" & Rows.Count).End(xlUp)(2).CopyFromRecordset rs
                    rs.Close
                End If
                fn = Dir
            Loop
        End With
    End Sub

  14. #14
    Registered User
    Join Date
    11-14-2022
    Location
    chennai
    MS-Off Ver
    2016
    Posts
    30

    Re: Copy specific columns from multiple files in folder and combine those columns in workb

    Hi Jindon,
    I have added the column header still is not working.
    for the second piece of code, i getting runtime error. It says problem with one or more formula references in this worksheet.
    Is the code search for random columns in the attached sheet?

  15. #15
    Registered User
    Join Date
    11-14-2022
    Location
    chennai
    MS-Off Ver
    2016
    Posts
    30

    Re: Copy specific columns from multiple files in folder and combine those columns in workb

    Hi Jindon,
    Nothing required, your code works now. I have copied your code in to new workbook, it works now.
    Is it possible to have list of column headers in other worksheet, instead of going to module and add? you amend in your first code. thanks so much for your help.

  16. #16
    Forum Guru
    Join Date
    08-15-2004
    Location
    Tokyo, Japan
    MS-Off Ver
    2013 O.365
    Posts
    22,834

    Re: Copy specific columns from multiple files in folder and combine those columns in workb

    I have tested the code before I posted, so it should work.
    Attached Files Attached Files

  17. #17
    Forum Guru
    Join Date
    08-15-2004
    Location
    Tokyo, Japan
    MS-Off Ver
    2013 O.365
    Posts
    22,834

    Re: Copy specific columns from multiple files in folder and combine those columns in workb

    In order to avoid any misunderstanding, you'd better to attach the workbook with the header somewhere and the sheet that receives the data.

  18. #18
    Forum Guru
    Join Date
    08-15-2004
    Location
    Tokyo, Japan
    MS-Off Ver
    2013 O.365
    Posts
    22,834

    Re: Copy specific columns from multiple files in folder and combine those columns in workb

    try change one line in "test" sub
            s = Array("Serial No.", "Country", "Overall status", "Other communications", "Domain Owner")
    to
            s = Filter(Sheets("Column header").[transpose(if(a1:a1000<>"",a1:a1000))], False, 0)

  19. #19
    Registered User
    Join Date
    11-14-2022
    Location
    chennai
    MS-Off Ver
    2016
    Posts
    30

    Re: Copy specific columns from multiple files in folder and combine those columns in workb

    Hi Jindon,
    I can able to get output only for first 3 workbooks not for remaining workbooks, there could be more than 30+ files in a folder. But the macro picking only 3 files. Do you know why?. i just followed the same procedure for all other files. I do not have any clue. please help. Thanks.

  20. #20
    Registered User
    Join Date
    11-14-2022
    Location
    chennai
    MS-Off Ver
    2016
    Posts
    30

    Re: Copy specific columns from multiple files in folder and combine those columns in workb

    1. The sheet name for all workbook is "owssvr"
    2. i have changed the columns in code based on my requirement, and ensure the columns are matching both in code and in all the files. I have done a check for one column by giving extra space to know whether it copy or not. But it is not copy all other columns because of one column error. I thought the code would pick other columns without the wrong column.
    Last edited by JaffarAhamed; 09-13-2023 at 03:15 AM. Reason: Grammer

  21. #21
    Forum Guru
    Join Date
    08-15-2004
    Location
    Tokyo, Japan
    MS-Off Ver
    2013 O.365
    Posts
    22,834

    Re: Copy specific columns from multiple files in folder and combine those columns in workb

    Sub test()
        Dim myDir As String, fn As String, i As Long, s(1)
        Dim cn As Object, rs As Object, x As Long
        Const wsName As String = "owssvr"
        With Application.FileDialog(msoFileDialogFolderPicker)
            If .Show Then myDir = .SelectedItems(1) & "\"
        End With
        If myDir = "" Then Exit Sub
        fn = Dir(myDir & "*.xlsx")
        Set cn = CreateObject("ADODB.Connection")
        Set rs = CreateObject("ADODB.Recordset")
        cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & myDir & fn & ";Extended Properties=""Excel 12.0;"""
        With Sheets("expected output")
            .[a1].CurrentRegion.ClearContents
            s(0) = Filter(Sheets("Column header").[transpose(if(a1:a1000<>"",a1:a1000))], False, 0)
            .[a1].Resize(, UBound(s(0)) + 1) = s(0)
            Do While fn <> ""
                s(1) = Cols("'" & myDir & "[" & fn & "]" & wsName & "'", s(0))
                If s(1) <> "" Then
                    rs.Open "Select " & s(1) & " From " & _
                        "`Excel 12.0;DataBase=" & myDir & fn & "`.`" & wsName & "$`;", cn
                    x = .Evaluate("max(if(" & .[a1].Address & "<>"""",row(" & .[a1].CurrentRegion.Address & ")))")
                    .Range("a" & x + 1).CopyFromRecordset rs
                    rs.Close
                End If
                fn = Dir
            Loop
        End With
    End Sub
    
    Function Cols(fn, s) As String
        Dim e, x, flg As Boolean
        If IsError(ExecuteExcel4Macro(fn & "!r1c1")) Then Exit Function
        For Each e In s
            x = ExecuteExcel4Macro("match(""" & e & """," & fn & "!r1:r1,0)")
            If IsError(x) Then
                Cols = Cols & ", Null"
            Else
                Cols = Cols & ", `" & Replace(e, ".", "#") & "`": flg = True
            End If
        Next
        If Not flg Then Exit Function
        If InStr(Cols, "`") = 3 Then Cols = Mid$(Cols, 3) Else Cols = Mid$(Cols, 2)
    End Function

+ 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. [SOLVED] Combine multiple sheets on basis of columns & copy to another workbook at specified sheet
    By sanjuss2 in forum Excel Programming / VBA / Macros
    Replies: 3
    Last Post: 09-21-2021, 10:13 AM
  2. [SOLVED] Copy specific columns from all excel files saved in selected folder
    By KKR1975 in forum Excel Programming / VBA / Macros
    Replies: 14
    Last Post: 09-03-2020, 11:03 PM
  3. loop through files find columns and copy/paste them as columns in master workbook
    By Michal1111 in forum Excel Programming / VBA / Macros
    Replies: 3
    Last Post: 07-18-2018, 10:40 PM
  4. [SOLVED] Copy specific columns from multiple workbooks to new workbook
    By nwix in forum Excel Programming / VBA / Macros
    Replies: 1
    Last Post: 09-03-2017, 10:48 AM
  5. [SOLVED] VBA to Copy the same Columns from multiple files in one folder
    By mcanant in forum Excel Programming / VBA / Macros
    Replies: 4
    Last Post: 01-16-2014, 03:15 AM
  6. Macro to combine multiple columns keeping few columns specific
    By lramesh in forum Excel Programming / VBA / Macros
    Replies: 0
    Last Post: 10-16-2013, 12:44 PM
  7. Opening all .csv files in a folder and deleting specific columns
    By jamesmac91 in forum Excel Programming / VBA / Macros
    Replies: 1
    Last Post: 11-30-2012, 11:20 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