使用VBA将多个txt批量转换成excel表并保存

VBA将多个txt批量转换成excel表并保存

Sub ykcbf() 
    Set fso = CreateObject("scripting.filesystemobject")
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    p = ThisWorkbook.Path & ""
    On Error Resume Next
    For Each f In fso.GetFolder(p).Files
        If f.Name Like "*.txt" Then
            fn = fso.GetBaseName(f)
            zrr = Split(ReadUTFText(f), Chr(13))
            ReDim brr(1 To 1000, 1 To 6)
            m = 0
            For i = 0 To UBound(zrr)
                If zrr(i) <> Empty Then
                    s = WorksheetFunction.Trim(zrr(i))
                    b = Split(s, ",")
                    m = m + 1
                    brr(m, 1) = b(0)
                    brr(m, 3) = b(4)
                    brr(m, 4) = b(1)
                    brr(m, 5) = fn
                    brr(m, 6) = b(2)
                End If
            Next
            Application.SheetsInNewWorkbook = 1
            Set wb = Workbooks.Add
            With wb.Sheets(1)
                .Columns(4).NumberFormatLocal = "@"
                .[a1:f1] = Array("姓名", "电话", "省份", "身份证号", "住址", "民族")
                .[a2].Resize(m, 6) = brr
                With .[a1].Resize(m + 1, 6)
                    .Borders.LineStyle = 1
                    .HorizontalAlignment = xlCenter
                    .VerticalAlignment = xlCenter
                    .EntireColumn.AutoFit
                End With
                .SaveAs p & fn
                .Close 1
            End With
        End If
    Next f
    Application.ScreenUpdating = True
    MsgBox "OK!"
End Sub


你可能感兴趣的:(excelVBA专栏,excel)