+ Reply to Thread
Results 1 to 6 of 6

How to Copy CSV Files to Current Workbook

Hybrid View

  1. #1
    Registered User
    Join Date
    01-12-2011
    Location
    Michigan, USA
    MS-Off Ver
    2010
    Posts
    16

    How to Copy CSV Files to Current Workbook

    I'm trying to loop through some CSV files that I'll be putting in a folder (usually around 20), and then copying them to different tabs in a master workbook. I've searched the hell out of Google trying to get the code I need to do this and putting things together from my own (apparently small amount of) knowledge. Eventually I'll have the macro do call another sub and do more, but right now I'm stuck on this simple/basic task.

    One piece of code I found is below. One problem is that "CurrentRegion" doesn't copy the whole worksheet, as there is a row of separation between some of the data. I wrote the commented out line of code below that to copy the worksheet, but pasting seemed to cause issues no matter which way I did it. With the current code as is, I get an error saying "Method 'Rows' of object '_Worksheet' failed." I've been banging my head against the wall trying different things to make this work. Please tell me where I went wrong either in this code or the other one that I've also tried.
    Sub ABC()
    Dim sPath As String, sName As String
        Dim bk As Workbook, r As Range
        Dim r1 As Range, sh As Worksheet
    
        Set sh = ActiveSheet  ' this is the summary sheet
        sPath = "H:\Macros\OR Reports\Macro OR Reports\"
        sName = Dir(sPath & "*.csv")
        Do While sName <> ""
           Set bk = Workbooks.Open(sPath & sName)
           Set r = bk.Worksheets(1).Range("A1").CurrentRegion
           'bk.Worksheets(1).Cells.Copy
           Set r1 = sh.Cells(sh.Rows.Count, 1).End(xlUp)(2)
           r.Copy
           r1.PasteSpecial xlValues
           r1.PasteSpecial xlFormats
           sh.Activate
           ActiveSheet.Paste
           bk.Close SaveChanges:=False
           sName = Dir()
        Loop
    End Sub
    Here's the first one that I tried. This one doesn't give me an error, but instead it pastes the entire contents of the Macro into a workbook named Book1, and there's also a Book2 left open at the end of the macro running with no data at all in it.

    Sub ORMaster()
        Dim lCount As Long
        Dim wbResults As Workbook
        Dim wbCodeBook As Workbook
    
    
        Application.ScreenUpdating = False
        Application.DisplayAlerts = False
        Application.EnableEvents = False
    
    
        Set masterBook = ActiveWorkbook
        
        On Error Resume Next
            Set wbCodeBook = ThisWorkbook
                With Application.FileSearch
                    .NewSearch
                    'Change path to suit
                    .LookIn = "H:\Macros\OR Reports\Macro OR Reports\"
                    .FileType = msoFileTypeAllFiles
                    'Optional filter with wildcard
                    '.Filename = "Book*.xls"
                        If .Execute > 0 Then 'Workbooks in folder
                            For lCount = 1 To .FoundFiles.Count 'Loop through all
                                'Open Workbook x and Set a Workbook variable to it
                                Set wbResults = Workbooks.Open(Filename:=.FoundFiles(lCount), UpdateLinks:=0)
                                
                                wbResults.Activate
                                ActiveSheet.Copy
                                masterBook.Activate
                                Set currentSheet = Worksheets.Add
                                currentSheet.Paste
                                
                                'DO YOUR CODE HERE
                                'ORMacro
    
                                wbResults.Close SaveChanges:=False
                            Next lCount
                        End If
                End With
        On Error GoTo 0
        Application.ScreenUpdating = True
        Application.DisplayAlerts = True
        Application.EnableEvents = True
    End Sub
    I would be extremely appreciative of someone being able to set me straight and point me in the right direction on this.

  2. #2
    Forum Guru
    Join Date
    03-02-2006
    Location
    Los Angeles, Ca
    MS-Off Ver
    WinXP/MSO2007;Win10/MSO2016
    Posts
    12,662

    Re: How to Copy CSV Files to Current Workbook

    ForSet r1 = sh.Cells(sh.Rows.Count, 1).End(xlUp)(2)
    Try:
    Set r1=sh.cells(Rows.Count,1).End(xlUp)
    Ben Van Johnson

  3. #3
    Registered User
    Join Date
    01-12-2011
    Location
    Michigan, USA
    MS-Off Ver
    2010
    Posts
    16

    Re: How to Copy CSV Files to Current Workbook

    Quote Originally Posted by protonLeah View Post
    ForSet r1 = sh.Cells(sh.Rows.Count, 1).End(xlUp)(2)
    Try:
    Set r1=sh.cells(Rows.Count,1).End(xlUp)
    When I try this, it gives me an error that says "Automation Error" and highlights that line of code in the debugger.

    Quote Originally Posted by JBeaucaire View Post
    As for the CurrentRegion issue, you might get better with this:

    Set r = bk.Worksheets(1).UsedRange
    Thanks! I believe this one will help once I can get the code to run.

  4. #4
    Forum Expert JBeaucaire's Avatar
    Join Date
    03-21-2004
    Location
    Bakersfield, CA
    MS-Off Ver
    2010, 2016, Office 365
    Posts
    33,492

    Re: How to Copy CSV Files to Current Workbook

    As for the CurrentRegion issue, you might get better with this:

    Set r = bk.Worksheets(1).UsedRange
    _________________
    Microsoft MVP 2010 - Excel
    Visit: Jerry Beaucaire's Excel Files & Macros

    If you've been given good help, use the icon below to give reputation feedback, it is appreciated.
    Always put your code between code tags. [CODE] your code here [/CODE]

    ?None of us is as good as all of us? - Ray Kroc
    ?Actually, I *am* a rocket scientist.? - JB (little ones count!)

  5. #5
    Forum Contributor arlu1201's Avatar
    Join Date
    09-09-2011
    Location
    Bangalore, India
    MS-Off Ver
    Excel 2003 & 2007
    Posts
    19,166

    Re: How to Copy CSV Files to Current Workbook

    Do you have a sample file that you can upload?
    If I have helped, Don't forget to add to my reputation (click on the star below the post)
    Don't forget to mark threads as "Solved" (Thread Tools->Mark thread as Solved)
    Use code tags when posting your VBA code: [code] Your code here [/code]

  6. #6
    Forum Expert JBeaucaire's Avatar
    Join Date
    03-21-2004
    Location
    Bakersfield, CA
    MS-Off Ver
    2010, 2016, Office 365
    Posts
    33,492

    Re: How to Copy CSV Files to Current Workbook

    This is how I would write this, does it work any better for you?
    Option Explicit
    
    Sub ABC()
    Dim sPath As String, sName As String
    Dim bk As Workbook, sh As Worksheet
    
        Set sh = ActiveSheet  ' this is the summary sheet
        sPath = "H:\Macros\OR Reports\Macro OR Reports\"
        sName = Dir(sPath & "*.csv")
    
        Do While Len(sName) > 0
            Set bk = Workbooks.Open(sPath & sName)
            Range("A1").UsedRange.Copy
            sh.Range("A" & Rows.Count).End(xlUp).Offset(1).PasteSpecial xlPasteValues
            sh.Range("A" & Rows.Count).End(xlUp).Offset(1).PasteSpecial xlPasteFormats
            bk.Close False
            sName = Dir()
        Loop
    
    
    End Sub

+ Reply to Thread

Thread Information

Users Browsing this Thread

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

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