• Skip to main content
  • Skip to header right navigation
  • Skip to site footer

My Online Training Hub

Learn Dashboards, Excel, Power BI, Power Query, Power Pivot

  • Courses
  • Pricing
    • Free Courses
    • Power BI Course
    • Excel Power Query Course
    • Power Pivot and DAX Course
    • Excel Dashboard Course
    • Excel PivotTable Course – Quick Start
    • Advanced Excel Formulas Course
    • Excel Expert Advanced Excel Training
    • Excel Tables Course
    • Excel, Word, Outlook
    • Financial Modelling Course
    • Excel PivotTable Course
    • Excel for Customer Service Professionals
    • Excel for Operations Management Course
    • Excel for Decision Making Under Uncertainty Course
    • Excel for Finance Course
    • Excel Analysis ToolPak Course
    • Multi-User Pricing
  • Resources
    • Free Downloads
    • Excel Functions Explained
    • Excel Formulas
    • Excel Add-ins
    • IF Function
      • Excel IF Statement Explained
      • Excel IF AND OR Functions
      • IF Formula Builder
    • Time & Dates in Excel
      • Excel Date & Time
      • Calculating Time in Excel
      • Excel Time Calculation Tricks
      • Excel Date and Time Formatting
    • Excel Keyboard Shortcuts
    • Excel Custom Number Format Guide
    • Pivot Tables Guide
    • VLOOKUP Guide
    • ALT Codes
    • Excel VBA & Macros
    • Excel User Forms
    • VBA String Functions
  • Members
    • Login
    • Password Reset
  • Blog
  • Excel Webinars
  • Excel Forum
    • Register as Forum Member

Loop function through directory of .txt files|VBA & Macros|Excel Forum|My Online Training Hub

You are here: Home / Loop function through directory of .txt files|VBA & Macros|Excel Forum|My Online Training Hub
Avatar
sp_LogInOut Log In sp_Registration Register
sp_Search Search
Advanced Search|Last Search Results
Search
Forum Scope




Match



Forum Options



Minimum search word length is 3 characters - maximum search word length is 84 characters
sp_Search Search
sp_RankInfo
Lost password?
sp_CrumbsHome HomeExcel ForumVBA & MacrosLoop function through directory of …
sp_PrintTopic sp_TopicIcon
Loop function through directory of .txt files
Avatar
R S

New Member
Members
Level 0
Forum Posts: 2
Member Since:
January 30, 2020
sp_UserOfflineSmall Offline
1
January 30, 2020 - 5:33 pm
sp_Permalink sp_Print

Hello Friends,

Requesting your help with VBA code to loop through a directory (simple folder holding a group of .txt files) to perform the below function on each .txt file. I was able to get the code to perform the function (shown below), but no idea how to create the code which will open each .txt file and have the contents copied and formatted onto an excel sheet from a directory. There may be 30+ files, hence, the loop is welcome.  Thank you so much!

FUNCTION TO BE PERFORMED--

Sub CopyFromNotePad()

'Copy .txt file into Excel

Dim wbI As Workbook, wbO As Workbook

Dim wsI As Worksheet

Set wbI = Workbooks.Open("INSERT EXCEL FILE PATH")

Set wsI = wbI.Sheets("Sheet2")

Set wbO = Workbooks.Open("INSERT.TXT FILE PATH")

wbO.Sheets(1).Cells.Copy wsI.Cells

wbO.Close SaveChanges:=False

Columns("A:A").Select

Selection.TexttoColumns Destination:=Range("A1"), DataType:=xlDelimited, _

TextQualifier:=xlDoubleQuote, Tab:=True, _

Other:=True, OtherChar _

:="|", FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, _

1), Array(6, 1), Array(7, 1), Array(8, 1), Array(9, 1), Array(10, 1), Array(11, 1), Array(12 _

, 1), Array(13, 1), Array(14, 1), Array(15, 1), Array(16, 1), Array(17, 1), Array(18, 1)), _

TrailingMinusNumbers:=True

Cells.Select

Cells.EntireColumn.AutoFit

Range("A1").Select

End Sub

Avatar
Purfleet
England
Member
Members


Trusted Members
Level 4
Forum Posts: 412
Member Since:
December 20, 2019
sp_UserOfflineSmall Offline
2
January 30, 2020 - 8:28 pm
sp_Permalink sp_Print

I have used something like the below a few times, it is formatted for my test textfiles and copies to the sheet 2 of the Macro workbook - you can then save this sheet separately as a next step.

I am not sure of your data but one issue with the below in its current state is it will copy everything including headings - this might be good or bad depending on what you are doing, but fairly easy to get rid with either resize or filter and delete

Sub CopyFromNotePad()

'Copy .txt file into Excel

Dim twb As String
Dim wbI As Workbook, wbO As Workbook

Dim TextFileLocation As String
Dim TextFile As String
Dim LastRow As Long

twb = ThisWorkbook.Name
TextFileLocation = "FULL ADDRESS OF FOLDER WITH TEXT FILES IN IT"
'TextFile = Dir(TextFileLocation & "*.txt")

TextFile = Dir(TextFileLocation)
Do While Len(TextFile) > 0

LastRow = Workbooks(twb).Worksheets("Sheet2").Cells(Rows.Count, 1).End(xlUp).Row + 1

Workbooks.OpenText (TextFileLocation & TextFile), DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, Tab:=True, Other:=True, _
OtherChar:="^", FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), Array(7, 1), Array(8, 1), _
Array(9, 1), Array(10, 1), Array(11, 1), Array(12, 1), Array(13, 1), Array(14, 1), Array(15, 1), Array(16, 1), Array(17, 1), Array(18, 1)), TrailingMinusNumbers:=True

Debug.Print Cells(Rows.Count, 1).End(xlUp).Row + 1

Range("A1").CurrentRegion.Copy Workbooks(twb).Worksheets("Sheet2").Range("a" & LastRow)

Workbooks(TextFile).Close False

TextFile = Dir

Loop

End Sub

Avatar
R S

New Member
Members
Level 0
Forum Posts: 2
Member Since:
January 30, 2020
sp_UserOfflineSmall Offline
3
January 31, 2020 - 9:02 am
sp_Permalink sp_Print

Hello Purfleet,

 

Thanks so much for your response. I tried running this but the macro did not produce a result, though it did not require debugging. It is possible I either failed to enter a file path or entered one were I shouldn't.  Can you provide a complete mock example along with fictional file paths and names?

Avatar
Philip Treacy
Admin
Level 10
Forum Posts: 1510
Member Since:
October 5, 2010
sp_UserOfflineSmall Offline
4
January 31, 2020 - 9:07 am
sp_Permalink sp_Print

Hi RS,

Have you tried stepping through the code to see what it is doing?

Debugging VBA

Regards

Phil

Avatar
Purfleet
England
Member
Members


Trusted Members
Level 4
Forum Posts: 412
Member Since:
December 20, 2019
sp_UserOfflineSmall Offline
5
January 31, 2020 - 4:42 pm
sp_Permalink sp_Print

R S said
Hello Purfleet,

 

Thanks so much for your response. I tried running this but the macro did not produce a result, though it did not require debugging. It is possible I either failed to enter a file path or entered one were I shouldn't.  Can you provide a complete mock example along with fictional file paths and names?  

It won't error if it cant find the folder it will just exit, you could put a counter in the loop to tell you how many files were imported

Did you put the full file path in here?

TextFileLocation = "FULL ADDRESS OF FOLDER WITH TEXT FILES IN IT"

To avoid going in to the code i have changed the macro slightly so that the file path is typed into cell B1 on sheet 1 and if not present will display a message and exit.

Attached is the workbook

It is also a good idea to step through the code together with the Debugging blog that Phil mentioned then you can work out what it is doing.

sp_Feed
Go to top
Forum Timezone: Australia/Brisbane
Most Users Ever Online: 245
Currently Online: Tristram Sexton, Christopher Anderson
Guest(s) 9
Currently Browsing this Page:
1 Guest(s)
Top Posters:
SunnyKow: 1432
Anders Sehlstedt: 870
Purfleet: 412
Frans Visser: 346
David_Ng: 306
lea cohen: 219
A.Maurizio: 202
Jessica Stewart: 202
Aye Mu: 201
jaryszek: 183
Newest Members:
yashal minahil
Oluwadamilola Ogun
Yannik H
dectator mang
Francis Drouillard
Orlando Inocente
Jovitha Clemence
Maloxat Axmatovna
Ricardo Freitas
Marko Meglic
Forum Stats:
Groups: 3
Forums: 24
Topics: 6200
Posts: 27182

 

Member Stats:
Guest Posters: 49
Members: 31861
Moderators: 3
Admins: 4
Administrators: Mynda Treacy, Philip Treacy, Catalin Bombea, FT
Moderators: MOTH Support, Velouria, Riny van Eekelen
© Simple:Press —sp_Information

Sidebar

Blog Categories

  • Excel
  • Excel Charts
  • Excel Dashboard
  • Excel Formulas
  • Excel PivotTables
  • Excel Shortcuts
  • Excel VBA
  • General Tips
  • Online Training
  • Outlook
  • Power Apps
  • Power Automate
  • Power BI
  • Power Pivot
  • Power Query
microsoft mvp logo
trustpilot excellent rating
Secured by Sucuri Badge
MyOnlineTrainingHub on YouTube Mynda Treacy on Linked In Mynda Treacy on Instagram Mynda Treacy on Twitter Mynda Treacy on Pinterest MyOnlineTrainingHub on Facebook
 

Company

  • About My Online Training Hub
  • Disclosure Statement
  • Frequently Asked Questions
  • Guarantee
  • Privacy Policy
  • Terms & Conditions
  • Testimonials
  • Become an Affiliate

Support

  • Contact
  • Forum
  • Helpdesk - For Technical Issues

Copyright © 2023 · My Online Training Hub · All Rights Reserved. Microsoft and the Microsoft Office logo are trademarks or registered trademarks of Microsoft Corporation in the United States and/or other countries. Product names, logos, brands, and other trademarks featured or referred to within this website are the property of their respective trademark holders.