簡體   English   中英

將目錄中的所有xlsx文件轉換為文本

[英]convert all xlsx files in directory to text

我正在嘗試在中創建按鈕。 xlsm會將myFolder目錄中的每個〜100 .xlsx文件轉換為.txt 下面的VBA代碼返回Expected End Sub錯誤。 即使可能存在其他工作表,數據也始終位於“工作表1”中。

Dos命令執行並轉換文件,但是它們不可讀(與excel格式有關嗎?)。 我不確定該怎么辦? 謝謝 :)

多斯

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

您代碼的第一行屬於Private Sub CommandButton1_Click()
(它必須由End Sub關閉)

Option Explicit和適當的代碼縮進可以在這種情況下提供幫助

試試這個版本:


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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM