2016-05-24 4 views
2

У меня есть несколько файлов txt в определенной папке, и я хочу преобразовать эти файлы в excel, выполнив txt в столбцы. Затем я хочу сохранить файлы excel отдельно в одной папке, удалив файлы txt и сохранив только файл excel. Мне нужен код VBA, который может это сделать, а также путем фильтрации пробелов в столбце A и удаления всех пробелов.как конвертировать несколько файлов txt и сохранять их в excel

Спасибо за вашу помощь

ответ

1

попробовать это *** НЕ ЗАБУДЬТЕ ИЗМЕНИТЬ ИМЯ ПАПКИ (Шпет) ****:

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 
+0

Спасибо dear..it, кажется, хорошо. Но есть небольшая проблема. Разделитель, который я должен использовать («{»), и я изменил код, как показано ниже: «Текст в столбцы - разделенный запятой txtBook.Sheets (1). Колонки (1) .TextToColumns Destination: = txtBook.Sheets (1). Ячейки (1, 1), DataType: = xlDelimited, _ Tab: = False, точка с запятой: = False, Comma: = False, Space: = False, Other: = ("{"), но имеют некоторую ошибку. Pls advise – vinmer

+0

Является ли разделитель {или ("{") ... –

+0

Плюс 'Other: = (" {")' следует изменить на 'Other: = True' и после этого' OtherChar: = "(" {") "' –

Смежные вопросы