2016-05-24 92 views
2

我在特定文件夾中有幾個txt文件,我想通過將txt轉換爲列來將這些文件轉換爲excel。然後,我想通過刪除txt文件並僅保留excel文件,將excel文件單獨保存在同一文件夾中。 我需要可以做到這一點的VBA代碼,也可以通過過濾A列中的空白並刪除所有的空白。如何轉換多個txt文件並將它們保存爲excel

感謝您的幫助

回答

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

謝謝dear..it似乎是不錯的。但是有一個小問題。我應該使用的分隔符(「{」)和我已經更改了代碼,如下所示:'Text to Columns - 逗號分隔 txtBook.Sheets(1).Columns(1).TextToColumns Destination:= txtBook.Sheets(1)。單元格(1,1),DataType:= xlDelimited,_ Tab:= False,Semicolon:= False,Comma:= False,Space:= False,Other:=(「{」)但有一些錯誤。請指教 – vinmer

+0

分隔符{或(「{」)... –

+0

Plus其他:=(「{」)'應該改爲'Other:= True',之後'OtherChar:=「(」{「 )'' –

相關問題