简体   繁体   English

使用Access VBA将Excel文件转换为文本

[英]Converting Excel files to Text using Access VBA

I am trying to save every .xls file in a folder location as text using Access VBA. 我试图使用Access VBA将文件夹中的每个.xls文件保存为文本。 I have patched together the code below. 我将以下代码修补在一起。 However, it only successfully saves the 1st excel file as text and then it seems to hang. 但是,它只能成功将第一个excel文件另存为文本,然后似乎挂起。

I have reviewed this post which I think achieves something similar to what I want: HERE .But I have been at this for so long that nothing is making sense!! 我已经审查了这篇文章,认为可以达到与我想要的类似的东西: HERE 。但是我已经从事了这么长时间,没有任何意义! Any ideas? 有任何想法吗? Is it getting stuck on ActiveWorkbook.Close ? 它是否卡在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

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. 通过在Set xlApp = New Excel.Application Excel。之后添加xlApp.Visible = True ,您发现Excel正在等待您告诉它是否覆盖与您要保存的文件同名的现有文件。

That happens because you assign a value to myfile just once ... 发生这种情况是因为您只为myfile分配了一个值...

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 ... ...但是然后重用相同的名称作为生成试图保存的每个.txt文件名称的基础...

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. 我认为您可以在那里替换objFile.Name ,因为它应该与当前工作簿文件的名称匹配……这意味着您的.txt文件名每次在For Each循环中都会有所不同。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM