vba 如果工作表不存在,则运行宏

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26516034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 04:57:16  来源:igfitidea点击:

Run Macros if Sheet Does Not Exist

excelvbaexcel-vba

提问by Kode

I am trying to only run a set of macros if a sheet doesn't already exist. I have a macro that creates a sheet and combines data from two sheets into it, and another that formats the new sheet. Since it needs to run on workbook open, I can't have it recreating the sheet again and again. I have been trying the following, but it gives the error: "sub or Function not defined":

如果工作表尚不存在,我试图仅运行一组宏。我有一个宏可以创建一个工作表并将两张工作表中的数据合并到其中,另一个用于格式化新工作表。由于它需要在工作簿打开时运行,我不能让它一次又一次地重新创建工作表。我一直在尝试以下方法,但它给出了错误:“子或函数未定义”:

Private Sub Workbook_Open()
If SheetExist("MyNewSheet") Then
End Sub
Else
Combine
Format
End Sub

回答by Jon Crowell

You aren't doing anything if the sheet exists, so change your test.

如果工作表存在,你什么都不做,所以改变你的测试。

Private Sub Workbook_Open()
    If Not SheetExist("MyNewSheet") Then
        Combine
        Format
    End If
End Sub

Function SheetExist(sheetname As String) As Boolean
    SheetExist = True ' replace this with code from link below
End Function

Use the answers here: Excel VBA If WorkSheet("wsName") Existsfor examples of functions that determine whether the sheet exists.

使用此处的答案:Excel VBA If WorkSheet("wsName") Exists用于确定工作表是否存在的函数示例。

回答by user1274820

Yea, the problem is "End Sub" should be "Exit Sub" You can also use the solution above/below.

是的,问题是“End Sub”应该是“Exit Sub”您也可以使用上面/下面的解决方案。

Your fixed code would be:

您的固定代码将是:

Private Sub Workbook_Open()

If SheetExists("MyNewSheet") Then
    Exit Sub
Else
    Combine
    Format
End If

End Sub

Also:

还:

Public Function SheetExists(ByVal WorksheetName As String) As Boolean 

On Error Resume Next
WorksheetExists = (Sheets(WorksheetName).Name <> "")
On Error GoTo 0

End Function