VBA to open, rename, close files in directory

df9864

Board Regular
Joined
Sep 28, 2004
Messages
108
Hi,
I have a large number of .txt files that get deposited in a directory. I'd like some code in Excel that will cycle through all the .txt files, open them and then close them in .xlsx format. (without any prompts, etc).
I know it's relatively simple but not sure how to cycle through files.

It's not a show-stopper, but would be good to point the code at a root folder which then has folders at the next level with the files in.
eg.
:\root folder\dir1\file1.txt
:\root folder\dir2\file2.txt
etc. where there can be any number or naming convention of folders under :\root folder
 

Excel Facts

Can you sort left to right?
To sort left-to-right, use the Sort dialog box. Click Options. Choose "Sort left to right"
Guess I might be asking too much.
Let me be more specific.
Once I've defined my 'folder', how do I read the underlying files to a variable where they have the following in common: *.txt
This is so I can 'loop' through them.

Also - is there an easy way to capture the 'root' of the filename (ie without the .txt) so I can later save them as .xlsx files? (once I've converted to the right format, etc).

Any help would be much appreciated - I've searched around historic questions but can't find anything on the money.

Thanks
 
Upvote 0
You could do something like this:-
Code:
[FONT=Courier New][SIZE=1]Sub LoopThroughFolder()[/SIZE][/FONT]
[FONT=Courier New][SIZE=1][/SIZE][/FONT] 
[FONT=Courier New][SIZE=1]  Const MyFolder As String = "[COLOR=red][B]C:\TEMP\[/B][/COLOR]"
  Const FileSpec As String = "[COLOR=red][B]*.txt[/B][/COLOR]"[/SIZE][/FONT]
[FONT=Courier New][SIZE=1]
  Dim MyFile As String
  Dim iDot As Integer
  Dim FileRoot As String
  Dim FileExt As String
  
  MyFile = Dir(MyFolder & FileSpec)
  Do While Len(MyFile) > 0
    iDot = InStrRev(MyFile, ".")
    If iDot = 0 Then
      FileRoot = MyFile
      FileExt = ""
    Else
      FileRoot = Left(MyFile, iDot - 1)
      FileExt = Mid(MyFile, iDot + 1)
    End If
  [/SIZE][/FONT][FONT=Courier New][SIZE=1][COLOR=green]  ' --------------------------------------------------------------------
    ' at this point your file name and its constituent parts are available
[/COLOR]    MsgBox "MyFolder=" & MyFolder & vbCrLf & "MyFile=" & MyFile & vbCrLf _
         & "FileRoot=" & FileRoot & vbCrLf & "FileExt=" & FileExt
[COLOR=green]    ' --------------------------------------------------------------------
[/COLOR]    MyFile = Dir
  Loop
    
End Sub[/SIZE][/FONT]
 
Upvote 0
Great post and I think i can use that in future. For what I'm working on now, I've used a different tact. It works well - but problem is that when it loops it goes back to the first file again.
I'm sure there's something very obvious here, but can't seem to spot it. Any ideas?

Code:
Sub Convert_txt_to_xlsx()
'
' Convert_txt_to_xlsx Macro

Dim strFolder As String
Dim strFile As String

strFolder = "H:\temp\txt_Files\"
strFile = strFolder & "*.txt"

Do While strFile <> ""
ChDir strFolder
Workbooks.OpenText Filename:= _
strFile, Origin:=xlMSDOS, StartRow _
:=1, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, Comma:=False _
, Space:=False, Other:=False, 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), Array(19, 1), Array(20, 1), Array(21, 1), Array(22, 1), _
Array(23, 1), Array(24, 1), Array(25, 1), Array(26, 1), Array(27, 1), Array(28, 1), Array( _
29, 1), Array(30, 1), Array(31, 1), Array(32, 1), Array(33, 1), Array(34, 1), Array(35, 1), _
Array(36, 1), Array(37, 1), Array(38, 1), Array(39, 1), Array(40, 1), Array(41, 1), Array( _
42, 1), Array(43, 1), Array(44, 1)), TrailingMinusNumbers:=True

Range(Selection, Selection.End(xlToRight)).Select

Selection.AutoFilter
With Selection
.HorizontalAlignment = xlGeneral
.VerticalAlignment = xlTop
.WrapText = True
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With

Cells.Select
Cells.EntireColumn.AutoFit

Range("A1").Select

ActiveWorkbook.SaveAs FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Close

Loop

End Sub
 
Upvote 0
If you're using Dir() to loop through the files in a folder you have to be careful not to modify the date/timestamp on the file otherwise Dir() gets fooled into thinking a new file has appeared and it will pick it up again.

Are you changing the date/timestamp of your 'original' files and picking them up again?

Or is Dir() picking up your newly-created files?

One solution would be to place the new files in a separate folder. You could always whizz though it at the end of the run and move the contents back to the original folder.

Is that any help?
 
Upvote 0
I appreciate your help.
I've never really understood how Excel 'knows' to move onto the next item when using a 'Do While / Loop' and not sure why in one set of code it moves on, and in the other it keeps reverting to the starting point.

I'm not a natural coder and the For x= 1 to y, next x approach is more intuitive.

However, I combined your code with mine and hey presto, it works !!

Thanks again.
D
 
Upvote 0
Thank You Ruddles!

I was looking for a loop to open files located in a directory and this worked perfectly for my needs. Went from a 40 minute process of clicking next a bunch of times to 5 minutes and one click.

Thanks again. The path I was on was much more complicated, unnecessarily so.
 
Upvote 0

Forum statistics

Threads
1,215,537
Messages
6,125,390
Members
449,222
Latest member
taner zz

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top