批量转换Excel到文本分隔文件

时间:2013-06-17 06:54:07

标签: excel-vba vba excel

您好我在处理将Excel电子表格转换为txt文件时遇到了问题。

我想要做的是创建一个宏,它可以将一个文件夹中的所有xls文件转换为txt文件。

目前正在处理的代码

Sub Combined()

  Application.DisplayAlerts = False

  Const fPath As String = "C:\Users\A9993846\Desktop\"
  Dim sh As Worksheet
  Dim sName As String
  Dim inputString As String

  With Application
    .Calculation = xlCalculationManual
    .EnableEvents = False
    .ScreenUpdating = False
  End With

  sName = Dir(fPath & "*.xls*")

  Do Until sName = ""
    With GetObject(fPath & sName)
      For Each sh In .Worksheets
        With sh
          .SaveAs Replace(sName, ".xls*", ".txt"), 42 'UPDATE:
        End With
      Next sh
      .Close True
    End With
    sName = Dir
  Loop

  With Application
    .Calculation = xlAutomatic
    .EnableEvents = True
    .ScreenUpdating = True
  End With
End Sub

但它没有按预期工作,我对VB有0个知识。谁愿意伸出援手?

2 个答案:

答案 0 :(得分:2)

以下代码将给定文件夹中的所有Excel工作簿(测试“xlsx”的文件扩展名)转换为CSV文件。文件名将是[workbookname] [sheetname] .csv,即“foo.xlsx”将获得“foo.xlsxSheet1.scv”,“foo.xlsxSheet2.scv”等。为了运行它,创建一个纯文本文件,将其重命名为.vbs并复制粘贴下面的代码。更改路径信息并运行它。

Option Explicit

Dim oFSO, myFolder
Dim xlCSV

myFolder="C:\your\path\to\excelfiles\"


Set oFSO = CreateObject("Scripting.FileSystemObject")
xlCSV = 6 'Excel CSV 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 & oWSH.Name & ".csv", xlCSV)
            Next
            Set oWSH = Nothing
            Call oWB.Close
            Set oWB = Nothing
        End If
    Next
    Call oExcel.Quit
    Set oExcel = Nothing

End Sub

如果需要,您可以提供更好的文件命名,错误处理等。

答案 1 :(得分:0)

您的代码的问题是您将sPath定义为包含通配符的路径:

sName = Dir(fPath & "*.xls*")

并仅替换扩展部分(.xls*),但在扩展名之前保留通配符:

Replace(sName, ".xls*", ".txt")

这会产生以下路径:

C:\Users\A9993846\Desktop\*.txt

会导致您观察到的错误,因为SaveAs方法会尝试将电子表格保存到文件名为*.txt的文件中,但*不是文件名的有效字符

替换它:

.SaveAs Replace(sName, ".xls*", ".txt"), 42

用这个:

Set wb = sh.Parent
basename = Replace(wb.FullName, Mid(wb.Name, InStrRev(wb.Name, ".")), "")
.SaveAs basename & "_" & sh.Name & ".txt", xlUnicodeText