20. VBA Tips - Import A Text File

A lot of VBA code is written to import files into spreadsheets.
- Today, we'll look at how to import a text file
Here's our text file, and we want to import it onto sheet1 of our spreadsheet starting at Range B7.
From this:
To this:
Here's the code we use:
Explanation:
- If you want to replicate this, download TextFile.TXT and save it to your C drive
- Download the example file
- Pressing the button will run the sub procedure: ImportTextFile
- The first thing we do is to set an object myTextFile equal to the opened text file
- The second line copies the data from the text file onto the spreadsheet
- The Copy method requires a source and a destination
- The Source is: myTextFile.Sheets(1).Range("A1").CurrentRegion
- This means: copy all the data that is linked to A1
- The destination is: ThisWorkbook.Sheets(1).Range("B7")
- After copying, we close the text file and the (FALSE) means don't save any changes.
Training Video on how to Import A Text File in Excel:
| Attachment | Size |
|---|---|
| import-a-text-file.xls | 39.5 KB |
| TextFile.TXT | 60 bytes |
»
- Nick's blog
- Add new comment
- 4432 reads

Search within opened text then copy part of it
How we can specify part of the text to be copied only?
for example Can we search to a keyword then imported on line only
search for piece of text...