首页 > 解决方案 > 检查列表中的现有工作表名称

问题描述

我想检查现有选项卡或工作表是否在选项卡名称列表中,例如在 A 列中。A 列位于名为 Import RPT 的选项卡中。

如果名称存在,我希望代码结束并创建一个 MsgBox,说明电子表格已经存在于 A 列的 i 行中,如果不继续。

我结合了 Stack Overflow 中的片段:

Dim sht As Worksheet, r As Range

With Sheets("Import RPT")
    For Each sht In Worksheets
        Set r = sht.Cells.Range("C2:C" & Count)
        If Application.WorksheetFunction.CountIf(Range("rngSheetInclusions"), sht.Name) > 0 Then
            strResult = strResult & "Duplicate Name: " & r & vbNewLine & "Rows: " & _
            Left(dict.Item(r), Len(dict.Item(r)) - 1) & vbNewLine & vbNewLine
            MsgBox strResul

    Next

标签: excelvba

解决方案


 Public Function SheetExists(s as string) As Boolean
     'Returns true if s is the name of a sheet in the current workbook
     On Error Goto NOPE
     Dim ws As Worksheet
     Set ws = ThisWorkbook.Sheets(s)
     SheetExists = True
     Exit function

 NOPE:
     SheetExists = False
 End function

一旦你有了这个功能,你可以=SheetExists(A1)在B1单元格输入,它会显示真假。然后向下拖动与选项卡名称相邻的 b 的其余部分


推荐阅读