0

如果工作簿存在于基于单元格条目的特定文件夹中,我已经编写了一些代码来启动它们。当条目为空白和/或文件中不存在该条目时,我无法显示错误消息。我尝试使用On Error GoTo MsgBox,但即使输入正确,也会显示 MsgBox。

Private Sub Worksheet_Change(ByVal Target As Range)

'PART NUMBER DECLARATIONS
Dim part1 As Long
Dim part2 As Long

'Variable Assignments
part1 = 123
part2 = 234

If Target.Address = "$G$9" Then

varCellvalue = Range("G9").Value

Workbooks.Open "C:\Users\USERX\Desktop\Test File\" & varCellvalue & ""

 ElseIF varCellvalue <> Range("G9").Value Then

MsgBox" Invalid Part Number"

End If


End Sub
4

3 回答 3

1

另一种方法不是使用错误处理,而是简单地检查文件是否存在,然后做出适当的响应:

Private Sub Worksheet_Change(ByVal Target As Range)
   'PART NUMBER DECLARATIONS
   Dim part1 As Long
   Dim part2 As Long

   'Variable Assignments
   part1 = 123
   part2 = 234

   If Target.Address = "$G$9" Then
      varCellvalue = "C:\Users\USERX\Desktop\Test File\" & Range("G9").Value & ""

      If Dir(varCellvalue) <> "" Then
         Workbooks.Open varCellvalue
      Else
         MsgBox "The file does not exist"
      End If
   End If
End Sub

我认为这种方法更干净,也许更直观。

于 2019-10-29T13:17:06.837 回答
0

有很多方法可以实现错误处理。这是一个……</p>

Private Sub Worksheet_Change(ByVal Target As Range)
    '… rest of your code

    On Error Goto ERR_FILE_OPEN
    Dim Wb As Workbook
    Set Wb = Workbooks.Open("C:\Users\USERX\Desktop\Test File\" & varCellvalue & "")
    On Error Goto 0 'don't forget to re-enable error reporting

    '… rest of your code

    Exit Sub
ERR_FILE_OPEN:
    MsgBox "File '" & varCellvalue & "' could not be opened.", vbCritical
End Sub

有关更多信息,请阅读:VBA 错误处理 - 完整指南


注意

If Target.Address = "$G$9" Then

不是测试单元格 G9 是否更改的非常可靠的方法。相反,始终使用 intersect 方法来测试范围是否已更改:

If Not Intersect(Me.Range("G9"), Target) Is Nothing Then
    varCellvalue = Me.Range("G9").Value
于 2019-10-29T13:05:34.737 回答
-1

实现错误检测的方法有很多,这里有一些流行的方法。

  1. Try-Catch 方法
' The "Try" part
On Error Resume Next
...
On Error GoTo 0
' The "Catch" part
If Err.Number <> 0 Then
...
End If
  1. On error Goto 方法
on error goto Oops
..
..
..
Exit Sub
Oops:
    'handle error here
End Sub

For a comprehensive approach, refer to further reading "VBA Error Handling – A Complete Guide." provided by PEH.
于 2019-10-29T13:11:28.313 回答