问题
I have this code below which partially works.
- Cats.txt (Contents: grey, blue, black)
- Dogs.txt (Contents: pink, red, orange)
- Cow.txt (Contents: black, white)
This is what I would like to get:
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim strPath As String
Dim strName As String
' Specify the folder...
strPath = "C:\Users\User\Desktop\TEST\"
' Use Microsoft Scripting runtime.
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(strPath)
' Check extension of each file in folder.
For Each objFile In objFolder.Files
If Right(objFile.Name, 4) = ".txt" Then
Cells(i + 1, 1) = objFile.Name
i = i + 1
End If
End Sub
Unfortunately I am unable to get the contents of the text file imported into column B. I have been looking online that I am a little bit unsuccessful to be honest.
回答1:
Try something like this. Make sure you add the reference to "Microsoft Scripting Runtime" ...
Option Explicit
Sub load()
' ADD REFERENCE TO MICROSOFT FILE SYSTEM OBJECT
Dim objFSO As FileSystemObject
Dim objFolder As Folder
Dim objFile As File
Dim objTextStream As TextStream
Dim strPath As String
Dim i As Long
' Specify the folder...
strPath = "C:\Users\User\Desktop\TEST\"
' Use Microsoft Scripting runtime.
Set objFSO = New FileSystemObject
Set objFolder = objFSO.GetFolder(strPath)
' Check extension of each file in folder.
For Each objFile In objFolder.Files
If objFSO.GetExtensionName(objFile.Name) = "txt" Then
Cells(i + 1, 1) = objFile.Name
Set objTextStream = objFile.OpenAsTextStream(ForReading)
Cells(i + 1, 2) = objTextStream.ReadAll
i = i + 1
End If
Next
End Sub
来源:https://stackoverflow.com/questions/61945419/import-text-files-contents-and-name-of-text-file-into-excel-with-a-macro