View Single Post
  #4   Report Post  
Posted to microsoft.public.excel.programming
Bob Phillips[_6_] Bob Phillips[_6_] is offline
external usenet poster
 
Posts: 11,272
Default How to read multiple text files into excel?

Hi,

I have amended the code to remove an un necessary test, and to open the
selected files.

Just copy the code below and paste in to a normal code module. Then run the
macro ProcessFiles. It will prompt you to select a directory, and when you
do, it will open all files in that directory. It won't do anything with them
other than open them , that's up to you

Option Explicit

Private Declare Function SHGetPathFromIDList Lib "shell32.dll" _
Alias "SHGetPathFromIDListA" _
(ByVal pidl As Long, _
ByVal pszPath As String) As Long

Private Declare Function SHBrowseForFolder Lib "shell32.dll" _
Alias "SHBrowseForFolderA" _
(lpBrowseInfo As BROWSEINFO) As Long

Private Type BROWSEINFO
hOwner As Long
pidlRoot As Long
pszDisplayName As String
lpszTitle As String
ulFlags As Long
lpfn As Long
lParam As Long
iImage As Long
End Type

Dim FSO As Object

Sub ProcessFiles()
Dim i As Long
Dim sFolder As String
Dim fldr As Object
Dim Folder As Object
Dim file As Object
Dim Files As Object

Set FSO = CreateObject("Scripting.FileSystemObject")

sFolder = GetFolder()
If sFolder < "" Then
Set Folder = FSO.GetFolder(sFolder)

Set Files = Folder.Files
For Each file In Files
If file.Type = "Text Document" Then
Workbooks.OpenText Filename:=file.path, _
Origin:=xlMSDOS, _
StartRow:=1, _
DataType:=xlDelimited, _
ConsecutiveDelimiter:=True, _
Space:=True
End If
Next file

End If ' sFolder < ""

End Sub


'-------------------------------------------------------------
Function GetFolder(Optional ByVal Name)
'-------------------------------------------------------------
Dim bInfo As BROWSEINFO
Dim path As String
Dim oDialog As Long

If IsMissing(Name) Then Name = "Select a folder."
bInfo.pidlRoot = 0& 'Root folder = Desktop

bInfo.lpszTitle = Name

bInfo.ulFlags = &H1 'Type of directory to Return
oDialog = SHBrowseForFolder(bInfo) 'display the dialog

'Parse the result
path = Space$(512)

GetFolder = ""
If SHGetPathFromIDList(ByVal oDialog, ByVal path) Then
GetFolder = Left(path, InStr(path, Chr$(0)) - 1)
End If

End Function

'----------------------------- end-script -----------------------------


--

HTH

Bob Phillips
... looking out across Poole Harbour to the Purbecks
(remove nothere from the email address if mailing direct)

"Together " wrote in message
...
Thank you for your nice help, Bob.
I am a new user for VBA in Excel. In fact, I could not understand your
code fully. Could you review it for me again. I can not run the code.

My sitation is that there are several tpyes file in one folder, such as
***.out, ***.fre, ***.trf. All the types can be opened by textscript.
Now I just use excel to open all the files, ***.out.