2017-07-04 12 views
0

私はボタンを作成しようとしています。 xlsmmyFolderディレクトリ内の〜100 .xlsxファイルをそれぞれ.txtに変換します。次のVBAコードはExpected End Subエラーを返します。ディレクトリ内のすべてのxlsxファイルをテキストに変換する

Dosコマンドは、ファイルを実行して変換しますが、読み込みできません(何がフォーマットに優れていますか?)やる?ありがとう:)

ドス

cd C:\Users\Desktop\folder 
Copy *.xlsx *.txt 

VBA

Option Explicit 

Private Sub CommandButton1_Click() 


Dim oFSO, myFolder 
Dim xlText 

myFolder = "C:\Users\Desktop\folder" 


Set oFSO = CreateObject("Scripting.FileSystemObject") 
xlText = -4158 'Excel txt format enum 
Call ConvertAllExcelFiles(myFolder) 
Set oFSO = Nothing 

Call MsgBox("Done!") 


Sub ConvertAllExcelFiles(ByVal oFolder) 
Dim targetF, oFileList, oFile 
Dim oExcel, oWB, oWSH 

Set oExcel = CreateObject("Excel.Application") 
oExcel.DisplayAlerts = False 
Set targetF = oFSO.GetFolder(oFolder) 
Set oFileList = targetF.Files 
For Each oFile In oFileList 
If (Right(oFile.Name, 4) = "xlsx") Then 
    Set oWB = oExcel.Workbooks.Open(oFile.Path) 
    For Each oWSH In oWB.Sheets 
     Call oWSH.SaveAs(oFile.Path & ".txt", FileFormat:=xlTextWindows) 
    Next 
    Set oWSH = Nothing 
    Call oWB.Close 
    Set oWB = Nothing 
End If 
Next 
Call oExcel.Quit 
Set oExcel = Nothing 
End Sub 

答えて

1


Option Explicit 

Private Sub CommandButton1_Click() 
    Dim myFolder As String 

    myFolder = "C:\Users\Desktop\folder" 
    ConvertAllExcelFiles myFolder 
    MsgBox "Done!" 
End Sub 

Public Sub ConvertAllExcelFiles(ByVal folderPath As String) 
    Dim xlApp As Object, wb As Workbook, ws As Variant, fso As Object 
    Dim fileList As Object, itm As Object, fileName As String 

    Set fso = CreateObject("Scripting.FileSystemObject") 
    Set fileList = fso.GetFolder(folderPath).Files 
    Set xlApp = CreateObject("Excel.Application") 
    xlApp.DisplayAlerts = False 

    For Each itm In fileList 
     If Right(itm.Name, 4) = "xlsx" Then 
      Set wb = xlApp.Workbooks.Open(itm.Path) 
      fileName = fso.GetParentFolderName(itm.Path) & "\" & fso.GetBaseName(itm.Path) 
      If True Then 'if converting all sheets use For loop (Change True to False) 
       wb.Sheets(1).SaveAs fileName & ".txt", FileFormat:=xlTextWindows 
      Else 
       For Each ws In wb.Sheets 
        ws.SaveAs fileName & " - " & ws.Name & ".txt", FileFormat:=xlTextWindows 
       Next 
       Set ws = Nothing 
      End If 
      wb.Close: Set wb = Nothing 
     End If 
    Next 
    xlApp.Quit 
End Sub 
:あなたのコードの最初の行

Option Explicitと適切なコードのインデント(それがEnd Subで閉じることがあります)Private Sub CommandButton1_Click()
に属しているが

このバージョンを試してみてください、このような状況で助けることができます


+1

ありがとうございました。 – Chris

+1

私はそれが助けてうれしいです。私は小さな変更を加え、テキストファイル名を改善しました。最初のバージョンはファイルを 'Book1.xlsx.txt'として保存しました(今は' Book1.txt'として保存しています) –

関連する問題