【问题标题】:Batch Convert TXT to XLS Using VBA使用 VBA 将 TXT 批量转换为 XLS
【发布时间】:2015-07-09 00:00:23
【问题描述】:

我正在尝试使用 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 文件。 (见Dir Function
  • 老哥,这个要你自己去发现!

标签: vba excel batch-file text


【解决方案1】:

您似乎在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

Dir Function

【讨论】:

    猜你喜欢
    • 2011-10-05
    • 1970-01-01
    • 1970-01-01
    • 2013-07-21
    • 1970-01-01
    • 2012-06-03
    • 1970-01-01
    • 2013-02-17
    • 2014-12-27
    相关资源
    最近更新 更多