如何在VBA中用Excel提示出错

我有一些代码在两个单独的工作簿中查找给定工作表名称的值。

我想要做的是当第一个工作簿没有工作表时,而不是下面的提示,它取消/抛出一个错误,并使用error handling去第二个电子表格。 我该怎么做呢?

工作表选择提示

目前我正在使用这个代码来实现这一点:

fFormString1 = "'" & wkBookRef1 & firstShtName & "'!$L$6/1000" fFormString2 = "'" & wkBookRef2 & firstShtName & "'!$L$6/1000" Application.DisplayAlerts = False 'Does nothing to the prompt On Error GoTo tryTwo 'Following only throws error when prompt is canceled ThisWorkbook.Sheets("Place").Range("E53").Formula = "=" & fFormString1 GoTo endTen tryTwo: ThisWorkbook.Sheets("Place").Range("E53").Formula = "=IFERROR(" & fFormString2 & ","""")" On Error Resume Next endTen: Application.DisplayAlerts = True 'Does nothing to the prompt 

注意:我希望在理想情况下closures电子表格。 或视觉上不存在,以提高我的客户的操作速度和平稳性。

从托马斯的回答中大量借款(全额抵免)。 但是,这似乎并没有为你工作。

使用ExecuteExcel4Macro但将其赋值给variablesval 。 然后检查这是否是您要查找的Error(2023)

请find下面的代码:

 'Check if the sheet exists in the workbook, used to check which forecast file one should look in Function ExtSheetExists(formString) As Boolean 'Form string is a formula string with both the worksheet and the workbook Dim val As Variant 'Tries to execute formula and throws error if it doesn't exist On Error Resume Next val = ExecuteExcel4Macro(formString) ExtSheetExists = (val <> Error(2023)) 'Returns False if the sheet does not exist based on Error 2023 On Error GoTo 0 End Function 

ExecuteExcel4Macro将从一个closures的工作簿中返回一个值。 如果工作表不存在,则会引发错误1004 'A formula in this worksheet contains one or more invalid references.

ExternalWorksheetExists使用它来testing工作表是否存在。

在这里输入图像说明

 Function ExternalWorksheetExists(FilePath As String, FileName As String, WorksheetName As String) As Boolean If Right(FilePath, 1) <> "\" Then FilePath = FilePath & "\" On Error Resume Next Call ExecuteExcel4Macro("'" & FilePath & "[" & FileName & "]" & WorksheetName & "'!R3C3") ExternalWorksheetExists = Err.Number = 0 On Error GoTo 0 End Function 

当使用ExecuteExcel4Macro ,所有引用必须以R1C1stringforms给出。 这是一个有效的string的例子:

 ExecuteExcel4Macro("'C:\Users\tinzina\Documents\[Book1.xlsm]Sheet1'!R6C12")