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

问题描述 投票:0回答:1

我有下面的代码,它只是打开一个文件。如果指定的teh lcoation中不存在该文件,则我需要出现错误消息。我遇到以下代码时遇到的麻烦是,当文件存在时,它会打开,在单元格A1中输入“Hello”,但仍然会出现MsgBox。我想我的出口Sub在错误的地方?

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
excel vba excel-vba error-handling
1个回答
2
投票

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
© www.soinside.com 2019 - 2024. All rights reserved.