0

In a previous question I asked about a method for importing .csv files using Excel using VBA. I received a helpful answer about opening .csv files using VBA, but I worry that using this method will cause issues with date formats, as a commenter on another of my questions mentioned. With that in mind, is there a similar method to the one used by Dan to import files? I understand that recorded macros are often clumsy and so I was wondering how something like the standard code below would be improved.

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

UPDATE:

The issue that occurs with the dates if I choose not to import is like so:

     DateTime               Format

     05/11/2014 3:22        Custom
4/27/2014 9:53:01 AM        General
     11/22/2013 8:29:35 AM  Custom
     05/11/2014 8:26        Custom
1/17/2014 12:28:24 PM       General
     05/11/2014 3:22        Custom

While this can be resolved when I import, if I simply open the file attempting to change the date format manually for the whole column doesn't actually change the format.

Community
  • 1
  • 1
114
  • 876
  • 3
  • 25
  • 51
  • Are the dates in the CSV formatted consistently? Or is your macro going to need to figure out the date format first? – CodeJockey May 19 '14 at 21:00
  • @CodeJockey They are all formatted MDY, with some containing a time as well. I don't think it would be a problem to treat them all as having a time attached, would it? – 114 May 19 '14 at 21:49
  • I've tangled with nasty dates before, but admittedly wound up using ruby to clean the CSVs. Can you show us what the MDY field looks like with some examples? – Dan Wagner May 20 '14 at 00:14
  • @Dan Sure, I'll show you what the mistake ends up being when I fail to change the dates during import as well. – 114 May 20 '14 at 15:39

1 Answers1

1

I wouldn't likely use this QueryTables method either, as @Dan-Wagner mentioned in your previous post. I would parse the file using something like a Text Stream object, found in the Microsoft Scripting Runtime library. You WILL have to add it as a reference (Tools-->References + find and select it from the list) See below for a little sample of how to use it:

Dim fileSys as New FileSystemObject 'the New keyword is important here!
Dim TS as TextStream
Dim txt as String, sp() as String   'first one is one string, second is an Array
Dim i as Integer

Set TS = fileSys.OpenTextFile("C:\myinputfile.csv")
i = 1
Do While Not TS.AtEndOfStream
    txt = TS.ReadLine               'Read one whole line of data
    sp = Split(txt, ",")            'Split by commas into "Cells" (kinda)
    Sheets(2).Cells(i, 1) = sp(0)     'Note, sp() is "Zero-Based" but ranges are 1 based
    Sheets(2).Cells(i, 2) = sp(1)     'So you'll always access sp onelower than myOutputRange
    '
    '
    '
    i = i + 1
Loop

Note that I assigned your output to the second worksheet, but you could use any range here.

MSDN TextStream Object: http://msdn.microsoft.com/en-us/library/aa242724%28v=vs.60%29.aspx Referencing Libraries: How do I use FileSystemObject in VBA?

Hope this helps!

Community
  • 1
  • 1
CodeJockey
  • 1,922
  • 1
  • 15
  • 20
  • Do you happen to know why I would be getting a "User-defined type not defined" error on fileSys? – 114 May 21 '14 at 19:57
  • You need to tell your macro where to find the definitions for the object. You can add a permanent reference by clicking on tools-->references and selecting "Microsoft Scripting Runtime" from the list. Alternatively, you can `Dim fileSys As Object` and call `Set fileSys = CreateObject("Scripting/FileSystemObject")` instead of `As New FileSystemObject` – CodeJockey May 21 '14 at 20:10
  • Thanks! The only issue now (and this is probably something trivial) is that I get a "sub not defined error" if I try to introduce the code as a subroutine, and if I don't include Sub() End Sub it opens up the macro browser. – 114 May 22 '14 at 15:59