【问题标题】:how to convert multiple txt files and saving them to excel如何转换多个txt文件并将它们保存到excel
【发布时间】:2016-05-24 14:16:10
【问题描述】:

我在特定文件夹中有多个 txt 文件,我想通过将 txt 转换为列来将这些文件转换为 excel。然后,我想通过删除 txt 文件并仅保留 excel 文件,将 excel 文件单独保存在同一文件夹中。 我需要可以做到这一点的 VBA 代码,还需要过滤 A 列中的空白并删除所有空白。

感谢您的帮助

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    试试这个***记得更改文件夹名称(spath)!****:

    Sub getTextFiles()
    
    Dim spath As Variant
    Dim sfile As Variant
    Dim lc As Variant
    Dim txtBook As Workbook
    Dim x As Variant
    Dim saveName As String
    
    Application.DisplayAlerts = False
    
    'IMPORTANT!!!!!
    'Set path to folder where you keep the text files
    spath = "C:\test\"
    
    'Loop through all text files in the folder
    sfile = Dir(spath & "*.txt")
    
    Do While sfile <> ""
    
        'Open the text file
        Set txtBook = Workbooks.Open(spath & sfile)
    
        'Text to Columns - comma separated
        txtBook.Sheets(1).Columns(1).TextToColumns Destination:=txtBook.Sheets(1).Cells(1, 1), DataType:=xlDelimited, _
        Tab:=False, Semicolon:=False, Comma:=True, Space:=False, Other:=False
    
        'Find last row with data
        lc = txtBook.Sheets(1).Cells(txtBook.Sheets(1).Rows.Count, "a").End(xlUp).Row
    
        'Loop through all rows in column "A" and delete the row if cell is blank
        For x = lc To 1 Step -1
            If txtBook.Sheets(1).Cells(x, 1) = "" Then txtBook.Sheets(1).Cells(x, 1).EntireRow.Delete
        Next x
    
        'Save file as xlsx and close it
    
        'File name without the ".txt" part
        saveName = Left(sfile, Len(sfile) - 4)
    
        txtBook.SaveAs Filename:=spath & saveName, FileFormat:=51, CreateBackup:=False
        txtBook.Close
    
    
        Set txtBook = Nothing
    
        'Delete old text file
        Kill spath & sfile
    
        'Get another file
        sfile = Dir()
    
    Loop
    
    Application.DisplayAlerts = True
    
    End Sub
    

    【讨论】:

    • 谢谢亲爱的..它似乎很好。但是有一个小问题。我应该使用的分隔符 ("{") 并且我已将代码更改如下:'Text to Columns - 逗号分隔 txtBook.Sheets(1).Columns(1).TextToColumns Destination:=txtBook.Sheets(1).Cells (1, 1), DataType:=xlDelimited, _ Tab:=False, 分号:=False, Comma:=False, Space:=False, Other:=("{") 但有一些错误。请建议
    • 加上Other:=("{") 应更改为Other:=True 之后OtherChar:="("{")"
    • 别忘了在OtherChar:="{"前加逗号!
    猜你喜欢
    • 2021-02-10
    • 2021-11-25
    • 1970-01-01
    • 2020-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多