Captain Smith
Active Member
- Joined
- Feb 28, 2003
- Messages
- 324
Hi. My objective is to import all .txt files located in a folder named output located on my desktop. The code below I mostly gleaned from this message board. I am running into a strange thing, however. Suppose I have 22 files in the output folder. The first time I run the macro it imports the 22 files correctly. If I then delete these files and replace them with 9 different files, the macro appears to try reading the same 22 files from the first time (it then gives me an error that it cannot find these files). Is there something I am missing here? Do I need to clear .FoundFiles.Count or something else in the beginning of my code?
Thanks much.
Sub Find()
Dim TmpDir, tmpdir1
TmpDir = CurDir()
ChDrive "C"
ChDir "\Documents and Settings\johnc\Desktop\output"
tmpdir1 = CurDir()
Location = tmpdir1
Application.DisplayAlerts = False
Set fs = Application.FileSearch
With fs
.LookIn = Location
.Filename = "*.txt"
If .Execute > 0 Then
MsgBox "There were " & .FoundFiles.Count & _
" file(s) found. Click OK to continue."
For I = 1 To .FoundFiles.Count
Workbooks.OpenText Filename:=.FoundFiles(I), Origin:= _
xlWindows, 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))
Next I
Else
MsgBox "There were no files found."
End If
End With
Call testIt
End Sub
Sub testIt()
Dim newWB As Workbook, aWB As Workbook
Set newWB = Workbooks.Add
For Each aWB In Application.Workbooks
If aWB Is newWB Or aWB Is ThisWorkbook Then
Else
aWB.Sheets(1).Move Before:=newWB.Sheets(1)
End If
Next aWB
SortWorksheets
End Sub
Thanks much.
Sub Find()
Dim TmpDir, tmpdir1
TmpDir = CurDir()
ChDrive "C"
ChDir "\Documents and Settings\johnc\Desktop\output"
tmpdir1 = CurDir()
Location = tmpdir1
Application.DisplayAlerts = False
Set fs = Application.FileSearch
With fs
.LookIn = Location
.Filename = "*.txt"
If .Execute > 0 Then
MsgBox "There were " & .FoundFiles.Count & _
" file(s) found. Click OK to continue."
For I = 1 To .FoundFiles.Count
Workbooks.OpenText Filename:=.FoundFiles(I), Origin:= _
xlWindows, 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))
Next I
Else
MsgBox "There were no files found."
End If
End With
Call testIt
End Sub
Sub testIt()
Dim newWB As Workbook, aWB As Workbook
Set newWB = Workbooks.Add
For Each aWB In Application.Workbooks
If aWB Is newWB Or aWB Is ThisWorkbook Then
Else
aWB.Sheets(1).Move Before:=newWB.Sheets(1)
End If
Next aWB
SortWorksheets
End Sub