如何*快速*将许多.txt文件转换为.xls文件

stu*_*iis 5 excel vba excel-vba

更新:我刚刚发现有一个功能更强大的服务器的人正在处理我被分配的任务,所以我没有让这个程序足够快.但是,下面的答案(自动化Excel)有助于使程序快三倍,所以我建议给那些文件较少(但仍然很多)的人.

我正在尝试将许多(超过300,000).txt文件转换为.xls文件.我在这里发现了如何做到这一点:

使用VBA批量转换TXT到XLS

但它真的很慢(在一个多小时内,它只转换了我们300,000个文件中的200个),即使文件不是那么大.

我试图通过关闭ScreenUpdating来加速它,但我无法成功关闭ScreenUpdating.有人可以解释在哪里关闭ScreenUpdating,以便我的代码运行得更快?或者,更好的是,任何更有效的计划的想法?

这是代码:

Sub TXTconvertXLS()

'Variables
Dim wb As Workbook
Dim strFile As String
Dim strDir As String

 Application.ScreenUpdating = False
'Directories
strDir = 'path went here
strFile = Dir(strDir & "*.txt")

 Do While strFile <> ""

    Set wb = Workbooks.Open(strDir & strFile)
        With wb
            .SaveAs Replace(wb.FullName, ".txt", ".xls"), 50
            .Close False   '<-already saved in the line directly above
        End With
    Set wb = Nothing
    strFile = Dir   '<- stuffs the next filename into strFile
Loop
Application.ScreenUpdating = True
End Sub
Run Code Online (Sandbox Code Playgroud)

bre*_*tdj 5

一些选项应该更快.

  1. 使用Powershell(将以下代码保存在记事本中,如xx.ps1,更新源目录并运行)
  2. 在隐藏的实例中而不是在当前的实例中自动执行Excel.

电源外壳

借鉴https://superuser.com/questions/875831/using-powershell-is-it-possible-to-convert-an-xlsx-file-to-xls使用Powershell循环浏览Excel文件并检查电子表格名称存在

$files = Get-ChildItem C:\Temp\*.txt
Write "Loading Files..."

$Excel = New-Object -ComObject Excel.Application
$Excel.visible = $false
$Excel.DisplayAlerts = $false

ForEach ($file in $files)
{

     $WorkBook = $Excel.Workbooks.Open($file.Fullname)
     $NewFilepath = $file.Fullname -replace ".{4}$"
     $NewFilepath =  $NewFilepath + ".xls"
     $Workbook.SaveAs($NewFilepath,56)   

}
  Stop-Process -processname EXCEL
  $Excel.Quit()
Run Code Online (Sandbox Code Playgroud)

自动化Excel

Sub TXTconvertXLS2()

Dim objExcel As Excel.Application
Dim wb As Workbook
Dim strFile As String
Dim strDir As String

Set objExcel = New Excel.Application
With objExcel
    .Visible = False
    .DisplayAlerts = False
End With

    'Directories
    strDir = "c:\temp\"
    strFile = Dir(strDir & "*.txt")

    'Loop
     Do While strFile <> ""
        Set wb = objExcel.Workbooks.Open(strDir & strFile)
            With wb
                .SaveAs Replace(wb.FullName, ".txt", ".xls"), 50
                .Close False   '<-already saved in the line directly above
            End With
        Set wb = Nothing
        strFile = Dir   '<- stuffs the next filename into strFile
    Loop

objExcel.DisplayAlerts = False
objExcel.Quit
Set objExel = Nothing

End Sub
Run Code Online (Sandbox Code Playgroud)