如何在VBA中使用Excel提示符引发错误

时间:2016-08-23 00:45:43

标签: excel excel-vba error-handling excel-addins vba

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

我想要做的是当第一个工作簿没有工作表时,而不是出现以下提示,它取消/抛出错误,并使用错误处理转到第二个电子表格。我该怎么做?

Sheet Select Prompt

目前我正在使用此代码来实现此目的:

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

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

1 个答案:

答案 0 :(得分:3)

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

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

enter image description here

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时,所有引用必须以R1C1字符串形式给出。以下是有效字符串的示例:

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