VBA to open .CSV files

Tim_Excel_

Well-known Member
Joined
Jul 12, 2016
Messages
512
Hi forum,

I have a vba module with which I want to open .CSV files delimited by the | character. I couldn't get it to work, so I instead worked around it by having excel open a nonsense file (.cvs, but it does work). Since this isn't very handy for the user, I'd like to look at it again and open .CSV files instead.
I came across this code:
Code:
<code>Sub ImportCSVFile(filepath As String)
    Dim line As String
    Dim arrayOfElements
    Dim linenumber As Integer
    Dim elementnumber As Integer
    Dim element As Variant

    linenumber = 0
    elementnumber = 0

    Open filepath For Input As #1 ' Open file for input
        Do While Not EOF(1) ' Loop until end of file
            linenumber = linenumber + 1
            Line Input #1, line
            arrayOfElements = Split(line, "|")

            elementnumber = 0
            For Each element In arrayOfElements
                elementnumber = elementnumber + 1
                Cells(linenumber, elementnumber).Value = element
            Next
        Loop
    Close #1 ' Close file.
End Sub
</code>
but it doesn't seem to open it delimited by the | character, plus it's being opened INSIDE the already opened workbook.

The code I have now:
Code:
     Workbooks.OpenText FileName:="" & inpt & "", _
        Origin:=65000, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
        xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=False _
        , Comma:=False, Space:=False, Other:=True, OtherChar:="|", FieldInfo _
        :=Array(Array(1, 1), Array(2, 1), Array(3, 2), Array(4, 1), Array(5, 1), Array(6, 1), _
        Array(7, 1), Array(8, 1), Array(9, 1), Array(10, 1), Array(11, 1)), _
        TrailingMinusNumbers:=True
this works perfectly with nonsense files, but refuses to work with .CSV files.
 

Excel Facts

Using Function Arguments with nested formulas
If writing INDEX in Func. Arguments, type MATCH(. Use the mouse to click inside MATCH in the formula bar. Dialog switches to MATCH.
I've seen this before and it's actually down to the file extension. When Excel "sees" a file with a CSV (Comma Separated Values afterall!) extension, it mandates that the text is separated by commas. Changing the file extension will work for your code. Alternatively, you could adapt the first piece of code to add a new workbook first:

Code:
Sub ImportCSVFile(filepath As String)
    Dim line As String
    Dim arrayOfElements
    Dim linenumber As Integer
    Dim elementnumber As Integer
    Dim element As Variant
    Dim newSheet As Worksheet


    linenumber = 0
    elementnumber = 0
    Set newSheet = Workbooks.Add().Sheets(1)


    Open filepath For Input As #1 ' Open file for input
        Do While Not EOF(1) ' Loop until end of file
            linenumber = linenumber + 1
            Line Input #1, line
            arrayOfElements = Split(line, "|")


            elementnumber = 0
            For Each element In arrayOfElements
                elementnumber = elementnumber + 1
                newSheet.Cells(linenumber, elementnumber).Value = element
            Next
        Loop
    Close #1 ' Close file.
End Sub

WBD
 
Upvote 0
WBD,

Although the code now opens in a new wb (thanks for that), the code actually puts everything in one line. It does delimit for the | character, but it just puts all characters after a | in a new column.
 
Upvote 0
Strange; it was working for me. Perhaps your "CSV" file does not have Windows line endings so "Line Input" just reads the whole thing in a single line? Alternatively you could copy the input file before importing it although then you're left with an extra file:

Code:
Sub ImportCSVFile(filePath As String)


FileCopy filePath, filePath & ".tmp"


Workbooks.OpenText Filename:=filePath & ".tmp", _
        Origin:=65000, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
        xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=False _
        , Comma:=False, Space:=False, Other:=True, OtherChar:="|", FieldInfo _
        :=Array(Array(1, 1), Array(2, 1), Array(3, 2), Array(4, 1), Array(5, 1), Array(6, 1), _
        Array(7, 1), Array(8, 1), Array(9, 1), Array(10, 1), Array(11, 1)), _
        TrailingMinusNumbers:=True


End Sub

WBD
 
Upvote 0
Thank WBD, this could work when I just delete that redundant file after the code has been executed. However, it's still a bit of a workaround. Anyhow, it seems this would be my only option.

If any other geniuses might see what's causing the problem, I'd be happy to hear it
 
Last edited:
Upvote 0
WBD,
I'm getting a 'Permission Denied' error, which is odd since in the same workbook I safe files to another directory. What's the cause of this error?
 
Last edited:
Upvote 0
Perhaps you don't have permission to create files in the same folder. This would use your TEMP folder:

Code:
Sub ImportCSVFile(filePath As String)

Dim tempFile As String

tempFile = Environ("TEMP")
If Right$(tempFile, 1) <> "\" Then tempFile = tempFile & "\"
tempFile = tempFile & Format$(Now, "yyyymmddhhmmss") & ".tmp"

FileCopy filePath, tempFile

Workbooks.OpenText Filename:=tempFile, _
        Origin:=65000, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
        xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=False _
        , Comma:=False, Space:=False, Other:=True, OtherChar:="|", FieldInfo _
        :=Array(Array(1, 1), Array(2, 1), Array(3, 2), Array(4, 1), Array(5, 1), Array(6, 1), _
        Array(7, 1), Array(8, 1), Array(9, 1), Array(10, 1), Array(11, 1)), _
        TrailingMinusNumbers:=True

End Sub

WBD
 
Upvote 0
I had already tried writing the destination path as the desktop, but this did not work either. This has me thinking I don't have permission to copy said file.. Odd
 
Upvote 0

Forum statistics

Threads
1,215,740
Messages
6,126,586
Members
449,319
Latest member
iaincmac

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top