Import text files contents and name of text file into Excel with a macro

强颜欢笑 提交于 2021-02-11 14:59:52

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!