访问VBA退出一个被叫子并跳过其余子

时间:2019-03-07 05:17:48

标签: vba exit

我有一个下面的子CreaNewT来创建一个新表。在CreatNewT中,我叫一个公共子ChecTabl来检查该表是否已经存在。

Sub CreaNewT()

Dim ...
Dim ...

Call ChecTabl("TableName")
...

ChecTabl中,我有

Dim TS As TableDefs
Dim T As TableDef

Set TS = CurrentDb.TableDefs

For Each T In TS
    If T.Name = Str_Tabl Then
        MsgBox "This table already exists. Please choose another table name.", vbOKOnly
        Exit Sub
    End If
Next

我写了Exit Sub是因为我想退出ChecTabl以及如果该表已经存在的情况下调用它的子程序。但是,它只会停止执行ChecTabl,并继续执行CreaNewT的其余部分。如何编码,使其停止执行ChecTabl和调用它的子程序?谢谢

1 个答案:

答案 0 :(得分:0)

感谢Tim,我将ChecTabl更改为布尔函数。我可以检查其返回值并决定是否退出调用此函数的子程序。

Public Function ChecTabl(Str_Tabl As String) As Boolean

    Dim TS As TableDefs
    Dim T As TableDef

    Set TS = CurrentDb.TableDefs

    For Each T In TS
        If T.Name = Str_Tabl Then
            MsgBox "This table already exists. Please choose another table name.", vbOKOnly
            ChecTabl = True
            Exit Function
        End If
    Next

    ChecTabl = False

Exit_Func:
    Set TS = Nothing
    Set T = Nothing

End Function