批量使用VBA将TXT转换为XLS

我正尝试使用VBA将一个包含.txt文件的目录转换为.xls。 我正在使用下面的代码:

Sub TXTconvertXLS() 'Variables Dim wb As Workbook Dim strFile As String Dim strDir As String 'Directories strDir = "\\xx\xx\xx\xx\Desktop\Test\Test1\" strFile = Dir(strDir & "*.txt") 'Loop Do While strFile <> "" Set wb = Workbooks.Open(strDir & strFile) With wb .SaveAs Replace(wb.FullName, ".txt", ".xls"), 50 .Close True End With Set wb = Nothing Loop End Sub 

问题是:当我运行它时,它立即表明已经有一个文件名称,它正试图保存在目录中。 即使在目录中确实没有.xls文件,它所显示的名称甚至具有.xls扩展名! 任何帮助将不胜感激 – 谢谢!

您好像在Loop之前丢失了strFile = Dir 。 没有它,你正在重新处理相同的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 

请参阅Dirfunction