gpt4 book ai didi

excel - 给定路径中缺少文件时的错误处理程序

转载 作者:行者123 更新时间:2023-12-04 20:43:49 25 4
gpt4 key购买 nike

我编写了一个 vba 代码来打开多个文件并复制这些文件的内容并将其粘贴到主文件中。当指定位置中缺少文件时,编译器会抛出错误,我可以处理并继续下一个文件。但是,如果第二次发生错误,程序将停止。

代码

On Error GoTo ErrH:

ErrH:
MsgBox strFileName & "is missing."
Sheets(strListSheet).Select
ActiveCell.Offset(1, 0).Select

GoTo Continue

最佳答案

有两种常见的方法来处理这样的错误

  • 单独的错误处理程序

  •     Dim wb As Workbook
    On Error GoTo ErrH
    For ' loop your File Names


    Set wb = Nothing
    Set wb = Workbooks.Open(strFileName)
    If Not wb Is Nothing Then
    ' Do your stuff

    End If
    Next 'strFileName
    Exit Sub
    ErrH:
    If Err.Number = 1004 Then
    ' File not found error
    Resume Next
    Else
    ' Handle other Errors
    MsgBox Err.Description
    End If
    End Sub
  • 内联错误处理程序

  •     Dim wb As Workbook
    On Error GoTo ErrH
    For ' loop your File Names


    Set wb = Nothing
    On Error Resume Next
    Set wb = Workbooks.Open(strFileName)
    On Error GoTo ErrH
    ' if wb is nothing then strFileName wasn't found
    If Not wb Is Nothing Then
    ' Do your stuff

    End If
    Next 'strFileName
    Exit Sub
    ErrH:
    ' Handle other Errors
    MsgBox Err.Description
    End Sub

    关于excel - 给定路径中缺少文件时的错误处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24988882/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com