Вы находитесь на странице: 1из 6

Sub DeepakCSV()

Dim FileContents As String, vFF As Long, vFile As String


Dim vRecords() As String, vTempArr() As Variant, vFileRecords() As String
Dim RecordCount As Long, FieldCount As Long, i As Long, j As Long

'pull entire text file into FileContents variable


vFile = "C:\deepak.csv"
vFF = FreeFile
Open vFile For Binary Access Read As #vFF
FileContents = Space$(LOF(vFF))
Get #vFF, , FileContents
Close #vFF

'split by record-delimiter
vRecords = Split(FileContents, vbCrLf)

'Create overall array to store entire text file's fields and records
' Note that this step is not necessary, just speeds up overall processing time

'Split each record by field delimiter


RecordCount = UBound(vRecords)
ReDim vTempArr(RecordCount)
For i = 0 To RecordCount
vTempArr(i) = Split(vRecords(i), ",")
Next

'determine max number of fields


FieldCount = 0
For i = 0 To RecordCount
If UBound(vTempArr(i)) > FieldCount Then FieldCount = UBound(vTempArr(i))
Next

'create 2 dimensional array to store all data


ReDim vFileRecords(RecordCount, FieldCount)
For i = 0 To RecordCount
For j = 0 To UBound(vTempArr(i))
vFileRecords(i, j) = vTempArr(i)(j)
Next
Next

'Transfer array data onto spreadsheet


Workbooks.Add
With Range("A1").Resize(RecordCount + 1, FieldCount + 1)
.NumberFormat = "@" 'make text format
.Value = vFileRecords
End With
End Sub

Reading text files in VBA

Reading text files (line by line)


Reading the text file line by line:

Visual Basic
1 Dim fileName As String, textData As String, textRow As String, fileNo As Integer
2 fileName = "C:\text.txt"
3 fileNo = FreeFile 'Get first free file number
4
5 Open fileName For Input As #fileNo
6 Do While Not EOF(fileNo)
7 Line Input #fileNo, textRow
8 textData = textData & textRow
9 Loop
10 Close #fileNo

Reading text files (read whole file)


Reading the whole text file into a string:

Visual Basic

1 Dim fileName As String, textData As String, fileNo As Integer


2 fileName = "C:\text.txt"
3 fileNo = FreeFile 'Get first free file number
4
5 Open fileName For Input As #fileNo
6 textData = Input$(LOF(fileNo), fileNo)
7 Close #fileNo

Reading CSV files in VBA

Reading CSV files (read whole file and process


each row)
Reading a text file line by line into a string:

Visual Basic
1 'Assuming file looks like this. File path: C:\test.csv
2 '"Col1", "Col2", "Col3"
3 '1 , 2 , 3
4
5 directory = "C:\"
6 fileName = "test.csv" 'Assuming test.csv is in C:\ directory
7 Set rs = CreateObject("ADODB.Recordset")
8 strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & directory & ";" _
9 & "Extended Properties=""text;HDR=Yes;FMT=Delimited"";"
10 strSQL = "SELECT * FROM " & fileName
11 rs.Open strSQL, strcon, 3, 3
12 rs.MoveFirst
13 Do
14 col1 = rs("Col1")
15 col2 = rs("Col2")
16 col3 = rs("Col3")
17 rs.MoveNext
18 Loop Until rs.EOF

Reading CSV files (whole file to Worksheet)


Read whole file to an Excel Worksheet:

Visual Basic

1 Dim ws as Worksheet, destRng as Range, fileName as String


2 fileName = "C:\text.txt"
3 Set destRng = Range("A1")
4 Set ws = ActiveSheet
5 With ws.QueryTables.Add(Connection:= "TEXT;" & fileName & "", Destination:=destRng)
6 .FieldNames = True
7 .RowNumbers = False
8 .FillAdjacentFormulas = False
9 .PreserveFormatting = True
10 .RefreshOnFileOpen = False
11 .RefreshStyle = xlInsertDeleteCells
12 .SaveData = True
13 .AdjustColumnWidth = True
14 .RefreshPeriod = 0
15 .TextFilePromptOnRefresh = False
16 .TextFilePlatform = 852
17 .TextFileStartRow = 1
18 .TextFileParseType = xlDelimited
19 .TextFileTextQualifier = xlTextQualifierDoubleQuote
20 'Select your delimiter - selected below for Comma
21 .TextFileConsecutiveDelimiter = False
22 .TextFileTabDelimiter = False
23 .TextFileSemicolonDelimiter = False
24 .TextFileCommaDelimiter = True
25 .TextFileSpaceDelimiter = False
26 .TextFileTrailingMinusNumbers = True
27 'This will refresh the query
28 End With
To refresh the CSV upload (in case the CSV was updated) simply run:

Visual Basic

1 ws.QueryTables.Refresh BackgroundQuery:=False

Reading binary files in VBA


Visual Basic

1 Dim fileName As String, fileNo As Integer, intVar As Integer


2 fileName = "C:\text.bin"
3 fileNo = FreeFile
4
5 Open fileName For Binary Lock Read As #fileNo
6 Get #fileNo, , intVar
7 Close #fileNo
With Binary files often you will be using objects which are not of fixed byte length like
Integers. For example you would want to read Strings from binary files
together with other data types. In such cases use the Type object data type when
writing to a file. Learn more here.
Below a simple example of reading a file to which a Type data type was
saved to, including an Integer and String.
Visual Basic
1 Type TestType
2 intVar As Integer
3 strVar As String
4 End Type
5
6 Sub ReadBinary()
7 Dim fileName As String, fileNo As Integer, testVar As TestType
8 fileName = "C:\test.bin"
9
10 fileNo = FreeFile
11 Open fileName For Binary Lock Read As #fileNo
12 Get #fileNo, , testVar
13 Debug.Print testVar.intVar 'Print the Integer
14 Debug.Print testVar.strVar 'Print the String
15 Close #fileNo
16 End Sub

Functions needed to read files in VBA


FUNCTION DESCRIPTION

Get next free file number available for the Open statement / FileOpen function. Using
this function is important especially when operating on multiple files simultaneously.
FreeFile More info here.

Returns true if you are at the beginning of the file described by the file number.
BOF(fileNumber) More info here.

Returns true if you have reached the end of the file described by the file number. More
EOF(fileNumber) info here.

Loc(fileNumber) Returns the current read/write position within an open file. More info here.

LOF(fileNumber) Returns the size in bytes of the file represented by the file number. More info here.
Sub WhatFileExtension()
Dim filExt As String
filExt = InputBox("What file extension?")
If filExt = "" Then Exit Sub
If InStr(filExt, "xls") = 0 Then Exit Sub
Workbooks.Open Filename:="C:\Users\Desktop\Excel." & filExt
End Sub