excel - 错误处理-在哪里输入 'Exit Sub'?

标签 excel vba error-handling

我有下面的代码,它只是打开一个文件。如果指定的文件中不存在该文件,那么我需要显示一条错误消息。我使用下面的代码遇到的麻烦是,当文件确实存在时,它将打开,在单元格A1中输入“Hello”,但是仍会出现MsgBox。我认为我在错误的位置放置了退出子???

Sub Test()

Dim Location As String
Dim File1 As String
Dim Err1 As String

On Error GoTo Err1
  Location = "S:\HRIS\Restricted\Information Services\Regular Reports\DRS _   
    Automation\" & Format(Date, "DD.MM.YYYY")
      File1 = "\Test.xlsx"
        Workbooks.Open FileName:=Location & File1

Range("A1").Value = "Hello"

Err1:
  MsgBox "Could not Locate " & Location & File1
Exit Sub

End Sub

最佳答案

Exit Sub移到Err1标签之前:

Sub Test()

    Dim Location As String
    Dim File1 As String
    Dim Err1 As String

    On Error GoTo Err1
        Location = "S:\HRIS\Restricted\Information Services\Regular Reports\DRS Automation\" & Format(Date, "DD.MM.YYYY")
        File1 = "\Test.xlsx"
        Workbooks.Open Filename:=Location & File1

    Range("A1").Value = "Hello"

    Exit Sub

Err1:
      MsgBox "Could not Locate " & Location & File1

End Sub

关于excel - 错误处理-在哪里输入 'Exit Sub'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52986820/

相关文章:

excel - 判断今天是否是星期一

excel - 识别单词中的模式

Excel VBA删除重复项保持定位

python - 尝试保存新文件: IndexError: list index out of range时发生Python错误

bash - errexit和bash中的管道

vba - 为什么这个 for 循环不处理完整的数据集?

python - 使用 pandas 和数据透视表更新 excel 文件

html - 如何为电子邮件格式化 html 表格

excel - 如何在VBA中查找日期之间的差异

c - 处理来自多个 fread 调用的错误的更简洁的方法