我有一个以下代码,用于从dir中存在的所有文件导入数据。我想将数据输入限制为.txt文件。即仅从文本文件导入。任何帮助。
Sub ReadFilesIntoActiveSheet()
Dim fso As FileSystemObject
Dim folder As folder
Dim file As file
Dim FileText As TextStream
Dim TextLine As String
Dim Items() As String
Dim i As Long
Dim cl As Range
' Get a FileSystem object
Set fso = New FileSystemObject
' get the directory you want
Set folder = fso.GetFolder("D:\workdir\NX12IP25_RenewDaimler\textfiles\t")
Set cl = ActiveSheet.Cells(1, 1)
For Each file In folder.Files
Set FileText = file.OpenAsTextStream(ForReading)
Do While Not FileText.AtEndOfStream
TextLine = FileText.ReadLine
Items = Split(TextLine, "|")
cl.Value = folder & "\" & file.Name
For i = 0 To UBound(Items)
cl.Offset(0, i + 1).Value = Items(i)
Next
Set cl = cl.Offset(1, 0)
Loop
FileText.Close
Next file
Set FileText = Nothing
Set file = Nothing
Set folder = Nothing
Set fso = Nothing
End Sub
答案 0 :(得分:2)
您应该使用If
语句检查最后4个字符是否为.txt
。你可以用两种方式做到这一点:
1)If Right(file.Name, 4) = ".txt" Then ...
或
2)使用正则表达式:If file.Name like "*.txt" Then ...
。
我更喜欢第一种解决方案,效率更高。
检查这个条件应该是你在循环中做的第一个操作,所以你会省略与我们的模式不匹配的文件(在这种情况下,不是文本文件)。
答案 1 :(得分:2)
您的主循环应如下所示:
For Each file In folder.Files
If Right(LCase(file.Name), 4) = ".txt" Then
Set FileText = file.OpenAsTextStream(ForReading)
Do While Not FileText.AtEndOfStream
TextLine = FileText.ReadLine
Items = Split(TextLine, "|")
cl.Value = folder & "\" & file.Name
For i = 0 To UBound(Items)
cl.Offset(0, i + 1).Value = Items(i)
Next
Set cl = cl.Offset(1, 0)
Loop
FileText.Close
End If
Next file
这将获取以.txt , .TXT , tXt
等结尾的文件。
答案 2 :(得分:2)
您可以通过直接检查文件名来执行此操作:
if LCase(Right(file.Name, 4) = ".txt") then
...
或让fileSystemObject为你的工作
if LCase(fso.getextensionname(File.Path)) = "txt" then
...
答案 3 :(得分:1)
如果仅限于文本文件,则可以使用DIR功能指定文件过滤器。第一次调用Dir时会找到与搜索模式匹配的第一个文件。再次调用它会再次返回具有相同模式的下一个文件,因此您可以循环直到它返回一个空字符串。
Dim file As String
file = Dir("D:\workdir\NX12IP25_RenewDaimler\textfiles\*.txt")
Do Until file = "" ' Start the loop.
Set FileText = file.OpenAsTextStream(ForReading)
Do While Not FileText.AtEndOfStream
TextLine = FileText.ReadLine
Items = Split(TextLine, "|")
cl.Value = folder & "\" & file.Name
For i = 0 To UBound(Items)
cl.Offset(0, i + 1).Value = Items(i)
Next
Set cl = cl.Offset(1, 0)
Loop
FileText.Close
file = Dir() ' Getting next entry.
Loop