1

我正在尝试使用 Access VBA 将文件夹位置中的每个 .xls 文件保存为文本。我已经将下面的代码拼凑在一起。但是,它只成功地将第一个 excel 文件保存为文本,然后它似乎挂起。

我已经查看了这篇文章,我认为它实现了与我想要的相似的东西:这里。但我已经在这个地方很久了,没有任何意义!有任何想法吗?卡住了ActiveWorkbook.Close吗?

 Public Sub FormatAsText()
Dim myfile As String
Dim xlApp As Excel.Application
Dim xlWB1 As Excel.Workbook

Dim objFso As FileSystemObject
Dim strPath As String
Dim objFolder As Folder
Dim objFile As File

        Set xlApp = New Excel.Application
        strPath = "C:FolderLocation..."

        Set objFso = CreateObject("Scripting.FileSystemObject")
        Set objFolder = objFso.GetFolder(strPath)

        myfile = Dir(strPath & "\*.xls")

            For Each objFile In objFolder.Files
                If objFile.Name Like "*.xls" Then
                    Workbooks.Open objFile, ReadOnly:=False
                    ActiveWorkbook.SaveAs FileName:=strPath & "\" & Replace(myfile, ".xls", ".txt"), FileFormat:=xlTextWindows
                    ActiveWorkbook.Close
                End If
            Next objFile

        Debug.Print myfile

Set xlApp = Nothing
Set xlWB1 = Nothing

Set objFso = Nothing

Set objFolder = Nothing
Set objFile = Nothing

End Sub
4

1 回答 1

2

By adding xlApp.Visible = True after Set xlApp = New Excel.Application you discovered Excel is waiting for you to tell it whether to overwrite an existing file which has the same name as the one you're trying to save.

That happens because you assign a value to myfile just once ...

myfile = Dir(strPath & "\*.xls")

... but then re-use that same name as the basis for generating the name of each .txt file you attempt to save ...

FileName:=strPath & "\" & Replace(myfile, ".xls", ".txt")

I think you can just substitute objFile.Name there because it should match the name of the current workbook file ... which means your .txt file name will be different each time through the For Each loop.

FileName:=strPath & "\" & Replace(objFile.Name, ".xls", ".txt")
于 2015-07-15T18:22:34.510 回答