gpt4 book ai didi

excel - 一个过程中有两个不同的错误处理程序

转载 作者:行者123 更新时间:2023-12-04 22:16:33 25 4
gpt4 key购买 nike

我有两个单独的错误处理程序。两者都查找是否打开了两个单独的工作簿。

Sub ErrHandler()
wbsource_name=ThisWorkbook.Worksheets("Sheet1").Range("A1").Value
wbdest_name=ThisWorkbook.Worksheets("Sheet1").Range("B1").Value

On Error GoTo Here
Set wb_source=Workbooks(wbsource_name)

Here:
MsgBox "Open main file"
Exit Sub

'I want here to stop first err handler
'The next file to be opened(or looked if is open)
'So if first file is open, but second not. It again gives the first error handler message

On Error GoTo 0
On Error GoTo Here2
Set wb_destination=Workbooks(wbdest_name)
Here2:
MsgBox "Open UPO file"
我用了 On error GoTo 0中和第一个错误处理程序,但它不起作用。
我也试过 On error Resume Next .
在一个子过程中使用两个不同的错误处理程序的任何想法。

最佳答案

我更喜欢将可能产生错误的操作推送到单独的方法中(特别是在主代码中重复该操作)。

Sub Tester()

Dim wbSrc As Workbook, wbDest As Workbook, wbsource_name As String, wbdest_name As String

wbsource_name = ThisWorkbook.Worksheets("Sheet1").Range("A1").Value
wbdest_name = ThisWorkbook.Worksheets("Sheet1").Range("B1").Value

Set wbSrc = GetOpenWorkbook(wbsource_name, "Workbook '" & wbsource_name & "' must be open")
If wbSrc Is Nothing Then Exit Sub

Set wbDest = GetOpenWorkbook(wbdest_name, "Workbook '" & wbdest_name & "' must be open")
If wbDest Is Nothing Then Exit Sub

End Sub

'Return an open workbook given its name, or Nothing if not found
' Optional message `msgMissing` to show if not found
Function GetOpenWorkbook(wbName As String, Optional msgMissing As String = "") As Workbook
On Error Resume Next
Set GetOpenWorkbook = Workbooks(wbName)
On Error GoTo 0
If GetOpenWorkbook Is Nothing And Len(msgMissing) > 0 Then
MsgBox msgMissing
End If
End Function

关于excel - 一个过程中有两个不同的错误处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68566905/

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