检查名称

时间:2018-04-19 22:54:09

标签: excel vba excel-vba

我想验证工作表是否存在,如果不存在,则要求用户输入从存在的工作表中选择工作表。查看this previous post上的信息,我想出了一个返回布尔值的函数,然后我会提示结果是否为假。

我遇到的问题是我输入的自定义工作表名称返回false,但默认的“Sheet1”...返回true。查看对象模型,我没有看到为Worksheets.Name.Value列出的并查看项目资源管理器,我看到这些工作表被列为`工作表1(宏变量)。

如何在括号中引用工作表的名称以便我的功能可以工作,或者如果不能使用工作表名称,是否有更好的解决方案?

这是我的代码

    Sub TestBed()
    Dim wb As Workbook, test As Boolean, debugStr As String, wsNames() As String
    Set wb = ThisWorkbook
    Debug.Print "List of sheets in this workbook"

    For i = 1 To wb.Worksheets.count
        ReDim Preserve wsNames(i - 1)
        wsNames(i - 1) = wb.Worksheets(i).Name
        debugStr = debugStr & wsNames(i - 1) & " | "
    Next i

    Debug.Print debugStr
    debugStr = ""

    For i = LBound(wsNames) To UBound(wsNames)
        test = ValidateWorksheetExists(wsNames(i), wb)
        debugStr = debugStr & wsNames(i) & " = " & test & " | "
    Next i

    Debug.Print debugStr
End Sub

Function ValidateWorksheetExists(sName As String, Optional wb As Workbook) As Boolean

If wb Is Nothing Then Set wb = ThisWorkbook

    With wb
        For i = 1 To .Worksheets.count
            If wb.Worksheets(i).Name = sName Then
                ValidateWorksheetExists = True
            Else
                ValidateWorksheetExists = False
            End If
        Next i
    End With
End Function

2 个答案:

答案 0 :(得分:2)

您需要在以下之后立即退出该功能:

ValidateWorksheetExists = True

否则i的下一次迭代会再次将其设置为False

(可能还有其他错误)

答案 1 :(得分:0)

虽然布尔变量(在这种情况下是错误的函数)在声明时默认为 False ,但最好是明确的......并且因为 ValidateWorksheetExists 从< strong> False ,无需再次将其设置为 False 。这样做会恢复在“ i ”之前的迭代中设置的可能 True 状态

Function ValidateWorksheetExists(sName As String, Optional wb As Workbook) As Boolean

If wb Is Nothing Then Set wb = ThisWorkbook

ValidateWorksheetExists = False

    With wb
        For i = 1 To .Worksheets.count
            If wb.Worksheets(i).Name = sName Then
                ValidateWorksheetExists = True
            End If
        Next i
    End With
End Function
相关问题