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

更新:我刚刚发现有一个更强大的服务器的人将在我被分配的任务上工作,所以我没有把这个程序做得足够快。 但是,下面的答案(自动化Excel)使程序的速度提高了三倍,所以我会把它推荐给那些文件较less(但还是很多)的人。

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

批量使用VBA将TXT转换为XLS

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

我试图通过closuresScreenUpdating来加快速度,但是我无法成功closuresScreenUpdating。 有人可以解释在哪里closuresScreenUpdating,以便我的代码将运行更快? 或者,更好的是,任何想法更有效的程序?

代码如下:

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 

一些应该更快的选项。

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

电源shell

https://superuser.com/questions/875831/using-powershell-is-it-possible-to-convert-an-xlsx-file-to-xls上绘图并使用Powershell循环浏览Excel文件,并检查电子表格名称存&#x5728;

 $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() 

自动化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