excel - 为什么此 VBA 代码中的执行未移至错误处理部分

标签 excel vba error-handling

我正在尝试将大量 xls 文件转换为 xlsx。我找到了一些代码 here我修改为 SaveAs采用新格式。但是,我的部分文件已损坏,无法打开。我想简单地跳过这些文件,所以我添加了注释中指出的行(以单词 ADDED 开头。

每次我运行代码时,我仍然会出现运行时错误,并显示无法打开文件的消息(对象工作簿的 1004 方法打开失败)。我使用调试按钮和 Set wb~声明被突出显示。我尝试了许多使用冒号的变体(我在 VBA 方面的经验很少)。

让我说清楚 - 无论 NextFile 之后是否有冒号,我都有相同的结果。 .

'Some code to pick the directory to work on and handle the case of no directory selected deleted for brevity

'Target File Extension (must include wildcard "*")
myExtension = "*.xls"

'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)

'Loop through each Excel file in folder
Do While myFile <> ""
    'Set variable equal to opened workbook
    'ADDED next line for error handling
    On Error GoTo NextFile:
    Set wb = Workbooks.Open(Filename:=myPath & myFile)

    'Ensure Workbook has opened before moving on to next line of code
    DoEvents 
    'Save Workbook as XLSX file and close
    saveFileName = Replace(myFile, ".xls", ".xlsx")
    wb.SaveAs Filename:=myPath & saveFileName, FileFormat:=xlOpenXMLWorkbook
    wb.Close   
    'Ensure Workbook has closed before moving on to next line of code
    DoEvents

    'Get next file name
    'ADDED next line for error handling
TryAgain:
    myFile = Dir
Loop

'removed some line that handle the end of the macro not needed for problem
'ADDED next line for error handling
Exit Sub
'ADDED next 2 lines for error handling    
NextFile:
    GoTo TryAgain
End Sub

现在这变得更加有趣了。我的初始测试文件夹中有 3,000 多个文件。导致错误(重复)的文件是序列中的第 121 个文件。因为我想在不等待三分钟的情况下处理这个问题(获取所需文件所花费的时间)我将 20 个文件移动到一个新目录 - 循环完成了所有文件的工作,它没有创建一个问题文件的 XLSX 版本。然后我在我的大目录上再次尝试并再次遇到同样的问题。我将尝试一次添加 10 个新文件,看看会发生什么。

最佳答案

正如 GSerg 所说,改变 GoTo TryAgainResume TryAgain应该修复它。

也就是说,更直观的布局可能是

Do While myFile <> ""
    Set wb = Nothing
    On Error Resume Next
        Set wb = Workbooks.Open(Filename:=myPath & myFile)
    On Error GoTo 0

    If Not wb Is Nothing Then
        'Save Workbook as XLSX file and close
        saveFileName = Replace(myFile, ".xls", ".xlsx")
        wb.SaveAs Filename:=myPath & saveFileName, FileFormat:=xlOpenXMLWorkbook
        wb.Close   
    End If
    myFile = Dir
Loop

另外,您是 Dir*.xls*并保存到您正在处理的同一目录中。这可能会返回新创建的 .xlsx文件。我建议更改为 myExtension = "*.xls"并保存到不同的文件夹。

关于excel - 为什么此 VBA 代码中的执行未移至错误处理部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57316902/

相关文章:

vba - 将字符串和数字连接为数字

PHP call_user_func_array 没有捕获数据库错误

error-handling - 如何在不使用 LISP 中的 remove 函数的情况下从列表中删除元素

powershell - PowerShell : Capturing Error for [IO.File]::ReadAllText

java - 如何在 Android Studio 中从 pdf 或 excel 文件导入联系号码?

vba - 在excel vba中的两个日期之间过滤

vba - 如何编辑 Access ADP 文件?

mysql - Excel-Vba 连接 Mysql localhost 失败

excel - 使用 Excel 工作表在 Cucumber 中进行数据驱动测试

excel - 在 Excel 2010 中的循环中嵌套 if..then 时遇到问题