我已经编写了一些代码来启动工作簿(如果它们基于单元格条目位于特定的文件夹中)。当条目为空白和/或文件中不存在错误消息时,我无法显示错误消息。我试过使用 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
答案 0 :(得分:0)
有许多方法可以实现错误处理。这是一个……
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 Error Handling – A Complete Guide。
请注意
If Target.Address = "$G$9" Then
不是测试单元格G9是否已更改的非常可靠的方法。而是始终使用相交方法来测试范围是否已更改:
If Not Intersect(Me.Range("G9"), Target) Is Nothing Then
varCellvalue = Me.Range("G9").Value
答案 1 :(得分:0)
代替使用错误处理,另一种方法是简单地检查文件是否存在,然后适当地响应:
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
我认为这种方法更清洁,也可能更直观。
答案 2 :(得分:-1)
有很多实现错误检测的方法,下面是几种流行的方法。
export class Store {
id?: string;
name: string;
address: string;
itemCount?: number;
rateCount?: number;
rating?: number;
constructor() {
}
}
' The "Try" part
On Error Resume Next
...
On Error GoTo 0
' The "Catch" part
If Err.Number <> 0 Then
...
End If