0

I am working on a macro to do some reformatting and editing of three workbooks. These three workbooks always have the same names, respectively, and come from the same source. They arrive in .csv format. What I would like is for VBA to import all three of these workbooks to one book as separate sheets, and rename these sheets based on a string found in the title of each workbook. Is there an easy way to append this to a recorded macro? Moreover, is there a better way of importing and delimiting / formatting the file than the way generated by recording a macro? I have placed the code from this method below:

With ActiveSheet.QueryTables.Add(Connection:= _
    "FAKENAME.csv" _
    , Destination:=Range("$A$1"))
    .CommandType = 0
    .Name = "FAKENAME"
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 65001
    .TextFileStartRow = 1
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = False
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = True
    .TextFileSpaceDelimiter = False
    .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, _
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 _
    , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1)
    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False
End With
Community
  • 1
  • 1
114
  • 876
  • 3
  • 25
  • 51
  • [You can start here for another approach](http://stackoverflow.com/questions/21010080/copying-data-from-a-text-file-to-an-excel-workbook/21010921#21010921). The link provides solution on loading multiple text files(which I think applies to CSV as well) and then copying it to a worksheet. – L42 May 17 '14 at 03:01

1 Answers1

1

I propose the following as a much easier method for opening CSVs and adding them to an output Workbook:

Option Explicit
Sub ImportCSVsToSheets()

Dim File As String, Path As String
Dim CSV As Workbook, Book As Workbook
Dim CS As Worksheet, Sheet As Worksheet
Dim LastRow As Long, LastCol As Long
Dim Source As Range, Target As Range

'set references up-front
Application.DisplayAlerts = False
Path = "c:\my\csv\files\"
File = Dir(Path & "*.csv")
Set Book = Workbooks.Add

'output workbook setup, make it bare-bones by deleting all non-first sheets
For Each Sheet In Book.Worksheets
    If Sheet.Index <> 1 Then
        Sheet.Delete
    End If
Next Sheet
Set Sheet = Book.Worksheets(1)
Sheet.Name = "DeleteMeSoon"

'loop through the CSVs and write data to sheets in output book
Do While Len(File) > 0
    'set up CSV and determine copy range
    Set CSV = Workbooks.Open(Path & File)
    Set CS = CSV.ActiveSheet
    With CS
        LastRow = .Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
        LastCol = .Cells.Find("*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
        Set Source = .Range(.Cells(1, 1), .Cells(LastRow, LastCol))
    End With

    'set up new sheet and destination range
    Set Sheet = Book.Worksheets.Add
    With Sheet
        Set Target = .Range(.Cells(1, 1), .Cells(LastRow, LastCol))
    End With

    'copy data from CSV to target
    Source.Copy Target

    'set the sheet name using the CSV file name
    Sheet.Name = Left(Left(File, Len(File) - 4), 31)

    'close the CSV and repeat
    CSV.Close SaveChanges:=False
    File = Dir
Loop

'remove that last pesky sheet
Set Sheet = Book.Worksheets("DeleteMeSoon")
Sheet.Delete

'save it however you'd like and boom we're done
'Book.SaveAs Filname:="a-file-name", FileFormat:=xlWhatever
Application.DisplayAlerts = True
End Sub
Dan Wagner
  • 2,693
  • 2
  • 13
  • 18
  • This looks good, but my only concern is that it opens the .csv files rather than importing them, which can cause trouble with the data. For example, dates commonly get incorrectly formatted (in a way that I do not know how to repair) if the file is opened rather than imported and changed to the relevant date type (in this case MDY). – 114 May 17 '14 at 16:22
  • Hmm... fixing values inside the CSV didn't seem like part of the original scope. Sooner or later, though, if your data is going to live in Excel, it will need to be formatted (as a date from the sounds of it) one way or another. I'm sure we can help -- perhaps in a new question? – Dan Wagner May 18 '14 at 22:10
  • That sounds good. It might also be that I am missing a way to ensure the dates are properly formatted, though I have tried many of the standard methods with no luck and was previously advised that I should always be importing and not opening .csv files. I will link this in a new post. – 114 May 19 '14 at 03:39