Vba read from excel file

You can VBA Read file binary or text data using a couple of different approaches in Excel. VBA provides you a set of native statements like Open to open and ready files. However in this article aside from showing you these native approaches to reading files using Excel Macros you can read CSV files and other structured data schemas using Jet.OLEDB driver, Microsoft Queries or also the FileSystemObject.

Text/binary files are common ways of storing data as opposed to databases or regular Excel files. Looking at various resources I missed a single resource which would demonstrate the various methods for PROPERLY reading files in VBA.

It is important to remember that you shouldn’t read all files using the same approach. Be aware of the structure of the file. If it is a structured CSV use the ADODB connection, if you need to read only a couple of rows read the file row by row or by chunks, else read the whole file. If you want performance – always select the right approach.

Reading text files in VBA

VBA Read text files (line by line)

To read an entire text file line by line use the code below.

Dim fileName As String, textData As String, textRow As String, fileNo As Integer
fileName = "C:text.txt"
fileNo = FreeFile 'Get first free file number  
    
Open fileName For Input As #fileNo
Do While Not EOF(fileNo)
   Line Input #fileNo, textRow
   textData = textData & textRow
Loop
Close #fileNo

VBA Read text files (read whole file)

To read an entire text file in one go (not line by line) use the code below.a

Dim fileName As String, textData As String, fileNo As Integer
fileName = "C:text.txt"
fileNo = FreeFile 'Get first free file number   
 
Open fileName For Input As #fileNo
textData = Input$(LOF(fileNo), fileNo)
Close #fileNo

VBA Read specific number of lines from a text file

In cases when you want to read specific lines from a text file you can adapt the line by line read code as below. It allows you to read a certain number of lines (noLines) from a text file from a specific start line number (sLine). If you set noLines to 0 it will read all lines till end of the file.

Dim fileName As String, textData As String, textRow As String, fileNo As Integer
Dim lineCounter as Long, sLine as Long, noLines as Long

fileName = "C:text.txt"

sLine = 20 'number of the first line you want to read
noLines = 100 'number of lines you want to read

fileNo = FreeFile 
Open fileName For Input As #fileNo
Do While Not EOF(fileNo)
  Line Input #fileNo, textRow
  If lineCount >= sLine and ((noLines > 0 and lineCount < noLines + sLine) or noLines = 0) then
    textData = textData &amp; textRow
  End If
  lineCount = lineCount + 1   
Loop
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:

'Assuming file looks like this. File path: C:test.csv
'"Col1", "Col2", "Col3"
'1     , 2     , 3

directory = "C:"
fileName = "test.csv" 'Assuming test.csv is in C: directory
Set rs = CreateObject("ADODB.Recordset")
strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & directory & ";" _
& "Extended Properties=""text;HDR=Yes;FMT=Delimited"";"
strSQL = "SELECT * FROM " & fileName 
rs.Open strSQL, strcon, 3, 3
rs.MoveFirst
Do
   col1 = rs("Col1")
   col2 = rs("Col2")
   col3 = rs("Col3")
   rs.MoveNext
Loop Until rs.EOF

Reading CSV files (whole file to Worksheet)

Read whole file to an Excel Worksheet:

Dim ws as Worksheet, destRng as Range, fileName as String
fileName = "C:text.txt"
Set destRng = Range("A1")
Set ws = ActiveSheet
With ws.QueryTables.Add(Connection:= "TEXT;" & fileName & "", Destination:=destRng)
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 852
    .TextFileStartRow = 1
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    'Select your delimiter - selected below for Comma
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = False
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = True
    .TextFileSpaceDelimiter = False
    .TextFileTrailingMinusNumbers = True
    'This will refresh the query
End With

To refresh the CSV upload (in case the CSV was updated) simply run:

  
ws.QueryTables.Refresh BackgroundQuery:=False

Reading binary files in VBA

Dim fileName As String, fileNo As Integer, intVar As Integer
fileName = "C:text.bin"
fileNo = FreeFile

Open fileName For Binary Lock Read As #fileNo
Get #fileNo, , intVar
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.

Type TestType
    intVar As Integer
    strVar As String
End Type

Sub ReadBinary()
    Dim fileName As String, fileNo As Integer, testVar As TestType
    fileName = "C:test.bin"

    fileNo = FreeFile
    Open fileName For Binary Lock Read As #fileNo
    Get #fileNo, , testVar
    Debug.Print testVar.intVar 'Print the Integer
    Debug.Print testVar.strVar 'Print the String
    Close #fileNo
End Sub

Reading XML files in VBA

XML files are basically text files which follow the XML taxonomy. You can try to read and process XML files similarly as text files shown above. However, given you will probably want to extract specific XML tag or attribute information I suggest reading my dedicated article below.

Functions needed to read files in VBA

Function Description
Open [path_to_file] For [Mode] [Access] [Lock] As [long_variable] Opens the file for read/write and returns the # file number (needs to be type of long) into long_variable
More info here. Parameters below:

  • Mode – Append, Binary, Input, Output, or Random
  • Access optional. Read, Write, or Read Write
  • Lock optional. Shared, Lock Read, Lock Write, and Lock Read Write.
Close Closes the file using the # file number.
More info here.
FreeFile Get next free file number available for the Open statement / FileOpen function. Using this function is important especially when operating on multiple files simultaneously.
More info here.
BOF(fileNumber) Returns true if you are at the beginning of the file described by the file number.
More info here.
EOF(fileNumber) Returns true if you have reached the end of the file described by the file number. More 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.

Above functions allow native upload of file data. However for more complicated scenario you will probably go for the FileSystemObject.

VBA Read File Summary

Reading files in VBA is not hard and requires just a few lines of code usually. It is, however, important to use the appropriate approach to read a file in VBA. Not all files need to be read line-by-line which is usually inefficient. Equally so you need not always read the entire file if you just need the first few / last rows. Working with XML files is also not a challenge if you read through my post on how to work with XML files.

Want to Write to files instead?

If you are looking to write to files instead using VBA, read my article on how to write to files using VBA.

Edit: After user3561813 the suggestion of adding "/", it now read the first file. I have an out of range error message "9". It does read the first file correctly. Ultimately I am trying to open each file, and read the name and age (this is a testing not the real production form). And retrieve the values back to my main worksheet.

enter image description here

Original question

I am trying to read hundred of excel forms in a folder, read a particular cell position, and record them into my testing worksheet. I googled this tutorial and tried to write my code. But when I execute the Getting Folder function, selected a folder path, it does not loop the excel files I have. (or record their names)

'Source: https://www.youtube.com/watch?v=7x1T4s8DVc0
Sub GettingFolder()
Dim SelectedFolder As String

With Application.FileDialog(msoFileDialogFolderPicker)
    .Title = "Select folder"
    .ButtonName = "Confirm"
    .InitialFileName = "U:"

    If .Show = -1 Then
        'ok clicked
        SelectedFolder = .SelectedItems(1)
        MsgBox SelectedFolder
        ' This is where I want to call my function
        LoopFiles (SelectedFolder)
    Else
        'cancel clicked
    End If
End With
End Sub

' Source: http://www.excel-easy.com/vba/examples/files-in-a-directory.html
Sub LoopFiles(path As String)
Dim directory As String, fileName As String, sheet As Worksheet
Dim i As Integer, j As Integer

' Avoid Screen flicker and improve performance
Application.ScreenUpdating = False
' Fixed per suggestion below..
directory = path & ""
fileName = Dir(directory & "*.xl??")

Do While fileName <> ""
    i = i + 1
    j = 2
    Cells(i, 1) = fileName
    Workbooks.Open (directory & fileName)
    For Each sheet In Workbooks(fileName).Worksheets
        Workbooks("Testing.xlsm").Worksheets(1).Cells(i, j).Value = sheet.Name
        j = j + 1
    Next sheet
    Workbooks(fileName).Close
    fileName = Dir()
Loop

' Reset the screen update setting
Application.ScreenUpdating = True
End Sub

VBA to Read Excel Data Using Connection String

Complete Excel VBA Course

Sometimes as a programmer you need to read heavy (more then 5 MB) Excel files. There are two ways you can read data from Excel files:

  • Open the file using VBA and read the data. Click Here

  • Stablish ADODB connection with Excel file and read data using SQL queries

Here I will be explaining how you can read heavy files with ADODB connection with Excel File and read data using SQL queries:

VBA Code to Read Excel Data using Connection String

Complete Excel VBA Course

Below is the VBA code which uses ADODB connection and reads data from Excel file:

'This function reads data from Excel file using ADODB connection
'Note: Microsoft ActiveX Data Objects 2.0 Library reference is required to run this code
Sub ReadFromExcel()
    '
    Dim strConString As String
    Dim strQuery As String
    Dim objCon As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim strDataSource As String
    Dim lCounter As Long
    '
    'Full path of the Excel file from which data needs to be read
    strDataSource = "E:WorkExcelSirJiPosts29. VBA Code to Read Excel Data using Connection StringDummy Data.xlsx"
    '
    'Define Connection string
    strConString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & strDataSource & "';Extended Properties=""Excel 12.0;HDR=YES;IMEX=1;"";"
    '
    'Set the SQL query
    'Things to note here: Data is the name of the sheet which needs to be followed by $ in the query
    '[Created At] > #01-01-2000# is the where clause which is optional
    strQuery = "SELECT * FROM [Data$] WHERE [Created At] > #01-01-2000#"
    '
    'Set the new instance of Connection and Recordset
    Set objCon = New ADODB.Connection
    Set rs = New ADODB.Recordset
    '
    'Open the connection
    objCon.Open strConString
    '
    'Run the SQL query and store the result in rs variable
    rs.Open strQuery, objCon, adOpenDynamic, adLockOptimistic
    '
    'Set the initial counter to 2nd row to paste the data
    lCounter = 2
    '
    'Read the data from recordset until it is not empty
    While rs.EOF = False
        Sheet1.Range("A" & lCounter).Value = rs.Fields(0) 'User Id
        Sheet1.Range("B" & lCounter).Value = rs.Fields(1) 'Full Name
        Sheet1.Range("C" & lCounter).Value = rs.Fields(2) 'Email
        Sheet1.Range("D" & lCounter).Value = rs.Fields(3) 'Department ID
        Sheet1.Range("E" & lCounter).Value = rs.Fields(4) 'Country
        Sheet1.Range("F" & lCounter).Value = rs.Fields(5) 'Created At
        Sheet1.Range("F" & lCounter).NumberFormat = "[$-en-US]d-mmm-yy;@" 'Change the cell format to date format
        Sheet1.Range("G" & lCounter).Value = rs.Fields(6) 'Created Time
        Sheet1.Range("G" & lCounter).NumberFormat = "[$-x-systime]h:mm:ss AM/PM" 'Change the cell formate to time format
        lCounter = lCounter + 1 'Increase the counter by 1
        rs.MoveNext 'Move the recordset to next record
    Wend
    '
    rs.Close 'Close the connect
    objCon.Close 'Close the recordset
    Set objCon = Nothing 'Release the variable from memory
    Set rs = Nothing 'Release the variable from memory
    'Show the confirmation to user
    MsgBox "Done"
    '
End Sub

To Use VBA Code Follow below steps:

Before:

VBA Code to Read Excel Data using Connection String

After:

VBA Code to Read Excel Data using Connection String

Download Practice File

You can also practice this through our practice files. Click on the below link to download the practice file.

Recommended Articles

  • Excel VBA Tool to Get File Properties
  • VBA Code to Re-link MS Access Link Tables
  • VBA Code to List Files in Folder
  • VBA Code to Check if File Exist in Folder
  • VBA Code to Add New Sheet at Beginning or End of Excel File

Secrets of Excel Data Visualization: Beginners to Advanced Course

Here is another best rated Excel Charts and Graph Course from ExcelSirJi. This courses also includes On Demand Videos, Practice Assignments, Q&A Support from our Experts.

This Course will enable you to become Excel Data Visualization Expert as it consists many charts preparation method which you will not find over the internet.

So Enroll now to become expert in Excel Data Visualization. Click here to Enroll.

Excel VBA Course : Beginners to Advanced

We are offering Excel VBA Course for Beginners to Experts at discounted prices. The courses includes On Demand Videos, Practice Assignments, Q&A Support from our Experts. Also after successfully completion of the certification, will share the success with Certificate of Completion

This course is going to help you to excel your skills in Excel VBA with our real time case studies.

Lets get connected and start learning now. Click here to Enroll.

Содержание

  1. Read Data from Text File
  2. VBA – Read Text File into String
  3. Read an Entire Text File into a String
  4. VBA Coding Made Easy
  5. VBA Code Examples Add-in
  6. VBA Read Text File (Read, Parse, and Import)
  7. Read Text File Content into Worksheet
  8. Read Text File Content Line by Line, Column by Column
  9. Read Text Files into Arrays
  10. VBA Coding Made Easy
  11. VBA Code Examples Add-in
  12. How to Read Data From Text File in Excel VBA?
  13. VBA Code:
  14. Analyst Cave
  15. VBA Read file in Excel (txt, xml, csv, binary)
  16. Reading text files in VBA
  17. VBA Read text files (line by line)
  18. VBA Read text files (read whole file)
  19. VBA Read specific number of lines from a text file
  20. Reading CSV files in VBA
  21. Reading CSV files (read whole file and process each row)
  22. Reading CSV files (whole file to Worksheet)
  23. Reading binary files in VBA
  24. Reading XML files in VBA
  25. Functions needed to read files in VBA
  26. VBA Read File Summary
  27. Want to Write to files instead?

Read Data from Text File

Below we will look at a program in Excel VBA that reads data from a text file. This file contains some geographical coordinates we want to import into Excel.

1. First, download the text file and add it to «C:test»

Place a command button on your worksheet and add the following code lines:

2. We declare four variables. myFile of type String, text of type String, textline of type String, posLat of type Integer, and posLong of type Integer.

3. We need to initialize the variable myFile with the full path and the filename.

use the GetOpenFilename method of the Application object to display the standard Open dialog box and select the file (without actually opening the file).

Note: the empty part between the brackets means we give Excel VBA nothing as input. Place your cursor on GetOpenFilename in the Visual Basic Editor and click F1 for help on the arguments.

4. Add the following code line:

Note: this statement allows the file to be read. We can refer to the file as #1 during the rest of our code.

5. Add the following code lines:

Note: until the end of the file (EOF), Excel VBA reads a single line from the file and assigns it to textline. We use the & operator to concatenate (join) all the single lines and store it in the variable text.

6. Close the file.

7. Next, we search for the position of the words latitude and longitude in the variable text. We use the Instr function.

8. We use these positions and the Mid function to extract the coordinates from the variable text and write the coordinates to cell A1 and cell A2.

Источник

VBA – Read Text File into String

This tutorial will demonstrate how to read a text file into a string in VBA.

We can either read the text file line by line or as an entire file.

Read an Entire Text File into a String

Text in a text file is usually made up of several lines, separated by delimiters. These can be a comma (“,”), a comma with space (“, “), a semicolon (“;”), a semicolon with space (“; “), a space (“ “), a tab (vbTab) or in rare cases any other character such as a tilde (

). The lines are normally separated by a line break (vbCRLF).

The easiest way to read an entire text file in VBA is to run the following code which will place the entire contents of the text file into a string variable. This procedure uses the VBA Open statement and the VBA FreeFile function.

We can also read a text file in VBA by using the FileSystemObject. In the code below we have used late binding with the File System Object.

We can also use early binding in the code and declare the File System Object by creating a reference in our Excel project to the File System Object.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

VBA Read Text File (Read, Parse, and Import)

In this Article

This tutorial will demonstrate how to read content from text files and paste it into worksheets with VBA.

Read Text File Content into Worksheet

The simplest way of reading a text file’s content is to copy it into a worksheet’s cell.

The above code uses the FileSystemObject. In order to use it, you will need to set a reference to the VB script run-time library. See here for more information.

Without using FileSystemObject you can paste your text file’s content with the below code. If your text file contains line separator, it will be pasted line by line.

Read Text File Content Line by Line, Column by Column

Your text file may have several rows and several elements listed in the rows separated by comma, semicolon, tab, space, etc.. In order to read and paste the text file’s content correctly, you may need this code below:

The delimiter that is used in your text file can be comma (“,”), comma with space (“, “), semicolon (“;”), semicolon with space (“; “), space (“ “), tab (change then Delimiter = vbTab) or in rare cases any other character.

Read Text Files into Arrays

If you need to read your text file’s content into an array and paste is line by line, column by column into your worksheet, you will need this code below:

Line separators in your text file can be carriage return and linefeed combination (Chr(13)+Chr(10)) or linefeed (Chr(10)). Use vbCrLf or vbLf, accordingly. If you are not sure, use vbNewLine for indicating the line separator.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

How to Read Data From Text File in Excel VBA?

VBA Program to read a Text file line by line (Sales Data) and places on a worksheet.

Sales Data in Text File: 5 Fields [ Product, Qtr 1, Qtr 2, Qtr 3 and Qtr 4 ] and 25 Records (Incl. header)

VBA code will read a text file and places on worksheet cells as below

VBA Code:

  • Declaring variables:
Variables Data Type Comments
line String Read text file line by line
Filename String Input file name (Full path)
i Integer Iterator
valueArr() String split the sentence by comma and store it in an array variable of type String
  • Initialize “Filename” variable with full path and filename
  • Open input file to read text
  • Read input file line by line
  • Split by comma and store it in valueArr(). In our example, each line has 5 values concatenated with comma.
  • Add text to respective cells from valuesArr(). Read each item in an array by it’s index value
  • Increment counter i, to move next line.
  • Close while loop
  • Close file

Approach:

Step 1: Open Excel.

Step 2: Add a shape (Read Text File) to your worksheet .

Step 3: Right-click on “Read Text file” and “Assign Macro..”

Step 4: Select ReadTextFileLineByLine Macro

Step 5: Save your excel file as “Excel Macro-Enabled Workbook” *.xlsm

Step 6: Click “Read Text file”

Step 7: Adjust column width in your excel file.

Источник

Analyst Cave

Simply the best place to learn Excel and Analytics

Home » VBA Read file in Excel (txt, xml, csv, binary)

VBA Read file in Excel (txt, xml, csv, binary)

You can VBA Read file binary or text data using a couple of different approaches in Excel. VBA provides you a set of native statements like Open to open and ready files. However in this article aside from showing you these native approaches to reading files using Excel Macros you can read CSV files and other structured data schemas using Jet.OLEDB driver, Microsoft Queries or also the FileSystemObject.

Text/binary files are common ways of storing data as opposed to databases or regular Excel files. Looking at various resources I missed a single resource which would demonstrate the various methods for PROPERLY reading files in VBA.

It is important to remember that you shouldn’t read all files using the same approach. Be aware of the structure of the file. If it is a structured CSV use the ADODB connection, if you need to read only a couple of rows read the file row by row or by chunks, else read the whole file. If you want performance – always select the right approach.

Reading text files in VBA

VBA Read text files (line by line)

To read an entire text file line by line use the code below.

VBA Read text files (read whole file)

To read an entire text file in one go (not line by line) use the code below.a

VBA Read specific number of lines from a text file

In cases when you want to read specific lines from a text file you can adapt the line by line read code as below. It allows you to read a certain number of lines (noLines) from a text file from a specific start line number (sLine). If you set noLines to 0 it will read all lines till end of the file.

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:

Reading CSV files (whole file to Worksheet)

Read whole file to an Excel Worksheet:

To refresh the CSV upload (in case the CSV was updated) simply run:

Reading binary files in VBA

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.

Reading XML files in VBA

XML files are basically text files which follow the XML taxonomy. You can try to read and process XML files similarly as text files shown above. However, given you will probably want to extract specific XML tag or attribute information I suggest reading my dedicated article below.

Functions needed to read files in VBA

Function Description
Open [path_to_file] For [Mode] [Access] [Lock] As [long_variable] Opens the file for read/write and returns the # file number (needs to be type of long) into long_variable
More info here. Parameters below:
  • Mode – Append, Binary, Input, Output, or Random
  • Accessoptional. Read, Write, or Read Write
  • Lockoptional. Shared, Lock Read, Lock Write, and Lock Read Write.

Close Closes the file using the # file number.
More info here. FreeFile Get next free file number available for the Open statement / FileOpen function. Using this function is important especially when operating on multiple files simultaneously.
More info here. BOF(fileNumber) Returns true if you are at the beginning of the file described by the file number.
More info here. EOF(fileNumber) Returns true if you have reached the end of the file described by the file number. More 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.

Above functions allow native upload of file data. However for more complicated scenario you will probably go for the FileSystemObject.

VBA Read File Summary

Reading files in VBA is not hard and requires just a few lines of code usually. It is, however, important to use the appropriate approach to read a file in VBA. Not all files need to be read line-by-line which is usually inefficient. Equally so you need not always read the entire file if you just need the first few / last rows. Working with XML files is also not a challenge if you read through my post on how to work with XML files.

Want to Write to files instead?

If you are looking to write to files instead using VBA, read my article on how to write to files using VBA.

Источник

Below we will look at a program in Excel VBA that reads data from a text file. This file contains some geographical coordinates we want to import into Excel.

Situation:

Read Data from Text File using Excel VBA

1. First, download the text file and add it to «C:test»

Place a command button on your worksheet and add the following code lines:

2. We declare four variables. myFile of type String, text of type String, textline of type String, posLat of type Integer, and posLong of type Integer.

Dim myFile As String, text As String, textline As String, posLat As Integer, posLong As Integer

3. We need to initialize the variable myFile with the full path and the filename.

myFile = «C:testgeographical-coordinates.txt»

or

use the GetOpenFilename method of the Application object to display the standard Open dialog box and select the file (without actually opening the file).

myFile = Application.GetOpenFilename()

Note: the empty part between the brackets means we give Excel VBA nothing as input. Place your cursor on GetOpenFilename in the Visual Basic Editor and click F1 for help on the arguments.

4. Add the following code line:

Open myFile For Input As #1

Note: this statement allows the file to be read. We can refer to the file as #1 during the rest of our code.

5. Add the following code lines:

Do Until EOF(1)
    Line Input #1, textline
    text = text & textline
Loop

Note: until the end of the file (EOF), Excel VBA reads a single line from the file and assigns it to textline. We use the & operator to concatenate (join) all the single lines and store it in the variable text.

6. Close the file.

Close #1

7. Next, we search for the position of the words latitude and longitude in the variable text. We use the Instr function.

posLat = InStr(text, «latitude»)
posLong = InStr(text, «longitude»)

8. We use these positions and the Mid function to extract the coordinates from the variable text and write the coordinates to cell A1 and cell A2.

Range(«A1»).Value = Mid(text, posLat + 10, 5)
Range(«A2»).Value = Mid(text, posLong + 11, 5)

9. Test the program.

Result:

Read Data from Text File Result

Return to VBA Code Examples

This tutorial will demonstrate how to read content from text files and paste it into worksheets with VBA.

Read Text File Content into Worksheet

The simplest way of reading a text file’s content is to copy it into a worksheet’s cell.

Sub FSOPasteTextFileContent() 
    Dim FSO As New FileSystemObject
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set FileToRead = FSO.OpenTextFile("C:TestTestFile.txt", ForReading) 'add here the path of your text file
    
    TextString = FileToRead.ReadAll
    
    FileToRead.Close
    
    ThisWorkbook.Sheets(1).Range("A1").Value = TextString 'you can specify the worksheet and cell where to paste the text file’s content

End Sub

The above code uses the FileSystemObject. In order to use it, you will need to set a reference to the VB script run-time library. See here for more information.

Without using FileSystemObject you can paste your text file’s content with the below code. If your text file contains line separator, it will be pasted line by line.

Sub PasteTextFileContent () 
    Dim wbExcel As Workbook, wbText As Workbook
    Dim wsExcel As Worksheet
    Set wbExcel = ThisWorkbook 'specify here which Excel file the text file’s content is to be pasted into
    Set wsExcel = wbExcel.Sheets(1) 'specify here which worksheet to use
    Set wbText = Workbooks.Open("C:TestTestFile.txt") 'add here the path of your text file

    wbText.Sheets(1).Cells.Copy wsExcel.Cells

    wbText.Close SaveChanges:=False

End Sub

Read Text File Content Line by Line, Column by Column

Your text file may have several rows and several elements listed in the rows separated by comma, semicolon, tab, space, etc.. In order to read and paste the text file’s content correctly, you may need this code below:

Sub PasteTextFileContentWithSeparators() 
    Dim StrLine As String
    Dim FSO As New FileSystemObject
    Dim TSO as Object
    Dim StrLineElements As Variant
    Dim Index As Long
    Dim i As Long
    Dim Delimiter as String
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set TSO = FSO.OpenTextFile("C:TestTestFile.txt")

    Delimiter=", " 'the delimiter that is used in your text file
    Index = 1

    Do While TSO.AtEndOfStream = False
       StrLine = TSO.ReadLine
       StrLineElements = Split(StrLine, Delimiter) 
       For i = LBound(StrLineElements) To UBound(StrLineElements)
           Cells(Index, i + 1).Value = StrLineElements(i) 'this code will start pasting the text file’s content from the active worksheet’s A1 (Cell(1,1)) cell
       Next i
       Index = Index + 1
    Loop

TSO.Close

End Sub

The delimiter that is used in your text file can be comma (“,”), comma with space (“, “), semicolon (“;”), semicolon with space (“; “), space (“ “), tab (change then Delimiter = vbTab) or in rare cases any other character.

Read Text Files into Arrays

If you need to read your text file’s content into an array and paste is line by line, column by column into your worksheet, you will need this code below:

Sub ReadDelimitedTextFileIntoArray()
    Dim Delimiter As String
    Dim TextFile As Integer
    Dim FilePath As String
    Dim FileContent As String
    Dim LineArray() As String
    Dim DataArray() As String
    Dim TempArray() As String
    Dim rw As Long, col As Long

    Delimiter = vbTab 'the delimiter that is used in your text file
    FilePath = "C:TestTestFileTab.txt"
    rw = 1 
    
    TextFile = FreeFile
    Open FilePath For Input As TextFile 
    FileContent = Input(LOF(TextFile), TextFile)
    Close TextFile

    LineArray() = Split(FileContent, vbNewLine) 'change vbNewLine to vbCrLf or vbLf depending on the line separator that is used in your text file
    For x = LBound(LineArray) To UBound(LineArray)
        If Len(Trim(LineArray(x))) <> 0 Then
           TempArray = Split(LineArray(x), Delimiter)
           col = UBound(TempArray)
 	   ReDim Preserve DataArray(col, rw)
           For y = LBound(TempArray) To UBound(TempArray)
 	       DataArray(y, rw) = TempArray(y)
 	       Cells(x + 1, y + 1).Value = DataArray(y, rw)  'this code will start pasting the text file’s content from the active worksheet’s A1 (Cell(1,1)) cell
           Next y
        End If 
        rw = rw + 1
     Next x

End Sub

Line separators in your text file can be carriage return and linefeed combination (Chr(13)+Chr(10)) or linefeed (Chr(10)). Use vbCrLf or vbLf, accordingly. If you are not sure, use vbNewLine for indicating the line separator.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

Excel Import Data From Another Workbook – VBA Codes

To pull data from an external Excel file, use on of these scenarios.

  1. Closed Excel file: Using VBA Import data with Workbook object
  2. Opened Workbook: Using VBA Read Excel file.
  3. External Reference within Worksheets.
  4. ODBC Data Import from another workbook.

Excel – Pull data from another Workbook using VBA

To understand how to get data from another Excel file, lets assume these 2 workbook names.

  • Source: In this workbook, VBA code will be executed to write or import data from/to Target file.
  • Target: This workbook has the data that the Source Workbook will read or modify through VBA.

1. VBA To Update Closed Workbook

This Excel vba import data from another workbook without opening the file manually.

First we will create an Workbook object to refer the external Excel file.  And use that object to import data into our Active workbook or Source Workbook.

Let’s see the actual VBA code for this purpose. Copy paste the below code to VB Editor and execute the code by pressing F5. Make sure that the Target file exists in correct path as mentioned in Target_Path in the code, before executing the code.

Sub VBA_Read_Data_Another_External_Workbook()

    '''''Define Object for Target Workbook
    Dim Target_Workbook As Workbook
    Dim Source_Workbook As Workbook
    Dim Target_Path As String
    
    '''''Assign the Workbook File Name along with its Path
    '''''Change path of the Target File name
    Target_Path = "D:Sample.xlsx"
    Set Target_Workbook = Workbooks.Open(Target_Path)
    Set Source_Workbook = ThisWorkbook
    
    '''''With Target_Workbook object now, it is possible to pull any data from it
    '''''Read Data from Target File
    Target_Data = Target_Workbook.Sheets(1).Cells(1, 1)
    Source_Workbook.Sheets(1).Cells(1, 1) = Target_Data
    
    '''''Update Target File
    Source_data = Source_Workbook.Sheets(1).Cells(3, 1)
    Target_Workbook.Sheets(1).Cells(2, 1) = Source_data
    
    '''''Close Target Workbook
    Source_Workbook.Save
    Target_Workbook.Save
    Target_Workbook.Close False
    
    '''''Process Completed
    MsgBox "Task Completed"
    
End Sub

2. VBA Read Excel file or Write To Open Workbook?

If a workbook is already in opened and executing, then you can reference that Excel with its name through ‘Workbooks’ collection. You have to use the workbook name itself inside the code to read or write content as mentioned in this sample code.

Sub Write_To_Open_Excel()
    Dim wb As Workbook
    
    'Reference Workbook with its name
    Workbooks("Book2").Worksheets("Sheet2").Activate
    Workbooks("Book3.xls").Worksheets("Sheet2").Activate
    
    'Search for Each Opened Workbook
    For Each wb In Workbooks
        If wb.Name = "Book2" Then
            wb.Sheets(1).Cells(1, 1) = "Writing To Open Excel Worksheet - Testing"
        End If
    Next
End Sub

3. External Reference to Import Data from another Workbook

With this technique, in the Excel we pull data from another cell by using references. For example, in Cell A1 if we need to get date from Cell B1, we enter “=B1” in cell A1. This is a reference that is made within the scope of current workbook.

In our example if we need to refer the Target sheet, use the command as below.

=’D:[sample.xlsx]Sheet1′!A2

This will fetch the data from the external workbook.

Reference from Microsoft: How to create External reference and pull data from another excel?

4. Data Import Option or ODBC in Excel VBA

This is similar to Data Import facility available in Excel. To do this, the Target workbook should be having some table defined in it.

To import the data from Target, Go to Source Workbook, Data->From Other Sources ->From Microsoft Query and Give the path of the Target Workbook or use the below code by modifying the File path and Column Header Details.

Sub Data_Import_Recorded_Macro()

    '''''Change File path and Column Headers to Use this code
    With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
        "ODBC;DSN=Excel Files;DBQ=D:Sample.xlsx;DefaultDir=D:;DriverId=1046;MaxBufferSize=2048;PageTimeout=5;" _
        , Destination:=Range("$A$1")).QueryTable
        .CommandText = Array( _
        "SELECT `Sheet1$`.Column1, `Sheet1$`.Column2, `Sheet1$`.Column3" & Chr(13) & "" & Chr(10) & "FROM `D:Sample.xlsx`.`Sheet1$` `Sheet1$`" _
        )
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .BackgroundQuery = True
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .PreserveColumnInfo = True
        .ListObject.DisplayName = "Table_Query_from_Excel_Files"
        .Refresh BackgroundQuery:=False
    End With
    
End Sub

These are some of the methods that are available to import from an external workbook to current active workbook. But still, this is not the limit.

Note: To read a Plain Text file or binary file, use VBA File Handling commands as in this link. How to Read contents from a Text File using VBA?

There might be other feasible methods known to others. If there is any, please post a reference as you find.

Понравилась статья? Поделить с друзьями:
  • Vba read excel line by line
  • Vba range from string excel
  • Vba programming excel to word
  • Vba for word forms
  • Vba for word and excel