2016-05-24 15 views
2

特定のフォルダに複数のtxtファイルがあり、これらのファイルをtxtから列に変換して変換する必要があります。次に、Excelファイルを個別に同じフォルダに保存するには、txtファイルを削除し、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)、データタイプ:= xlDelimited、_ タブ:= False、セミコロン:= False、カンマ:= False、スペース:= False、その他:=( "{") Plsは助言する – vinmer

+0

区切り記号{または( "{")... –

+0

プラス 'Other:=(" {")'は 'Other:= True'に変更し、' OtherChar:= "(" {" ) "' –

関連する問題