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.
Here's the code we use:
- 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: