将管道分隔的txt文件转换为xlsx

时间:2014-08-21 23:24:11

标签: excel excel-vba batch-file file-conversion vba

我必须将40多个管道分隔的.txt文件转换为Excel工作表(.xlsx)。此外,所有字段在转换时都应视为文本。以下是我发现最有效的手动方式。假设我有sample1.txt文件到... sampleN.txt。

1. Drag sample1.txt file to empty workbook. Then it creates new workbook with single sheet with sheet name same as sample1 copying all lines in file under column A.
2. Select column A and use text to column wizard.
3. Choose delimited file with pipe (|) delimiter and select text data type after selecting all column in next wizard tab. Then Finish.
4. File 'Save as' sample1.xlsx

录制宏后,我可以使用单键组合执行步骤2到4。但是" sample1"在宏中得到硬编码。因此,每次我必须适当地重命名保存的文件。是否有任何方法可以在&#34期间根据当前工作表名称获取文件名;另存为"?有没有更好,更简单的方法来做这一切?可能像批处理模式等。

1 个答案:

答案 0 :(得分:0)

我经常使用一个宏来循环浏览文件夹。请注意,如果尝试使用所有文件(而不仅仅是文本文件),那么我通常会创建一个专门用于导入的文件夹。

文件夹路径在宏中是硬编码的(可以更改它以显示文件夹对话框。然后检查以确保路径有效,然后循环遍历每个文件做某事,关闭文件,最后它会打印打开的文件数。

Sub process_folder()
Dim book_counter As Integer
Dim folder_path As String
Dim pWB As Workbook, sWB As Workbook, sWB_name As String
Dim pWS As Worksheet

    book_counter = 0

    Set pWB = ActiveWorkbook
    Set pWS = pWB.ActiveSheet

    folder_path = "C:\a"

    folder_path = verify_folder(folder_path)
    If folder_path = "NULL" Then
        Exit Sub
    End If

    'Get first file to open
    sWB_name = Dir(folder_path, vbNormal)

    'Loop through files
    Do While sWB_name <> ""

        'Open each file
        Workbooks.Open Filename:=folder_path & sWB_name
        Set sWB = Workbooks(sWB_name)

        '''''''''''''''''''''''''
        'Do stuff here (this just prints the file name)
        MsgBox (sWB.Sheets(1).Name)
        '''''''''''''''''''''''''

        'close file increment counter
        sWB.Close (False)
        sWB_name = Dir()
        book_counter = book_counter + 1
    Loop

    'Number of files processed
    MsgBox ("Number of Fragment Files processed: " & book_counter)


End Sub


Function verify_folder(path As String) As String

    If path = "" Then
        MsgBox ("Enter a Directory to process")
        verify_folder = "NULL"
        Exit Function
    End If

    If Not PathExists(path) Then
        MsgBox ("Directory does not exist")
        verify_folder = "NULL"
        Exit Function

    End If

    If Right(path, 1) <> "\" Then
            verify_folder = path & "\"
    End If

End Function

Function PathExists(pName) As Boolean
On Error Resume Next
    PathExists = (GetAttr(pName) And vbDirectory) = vbDirectory
End Function