Excel VBA +循环播放工作表,如果工作表名称如图案,则重命名工作表

时间:2016-07-23 03:11:24

标签: excel-vba loops design-patterns vba excel

我正在尝试遍历工作表,如果工作表名称找到了模式,我想重命名它。

以下是代码,但是,它没有重命名。但是,字符串模式不起作用。我也尝试通过表单的确切名称来完成它,但它仍然没有进入Select Case语句

请注意," * BE Con​​sol"确实考虑了空间

For myforecastSheetsIndex = LBound(myforecastSheetsArray) To UBound(myforecastSheetsArray)

Select Case myforecastSheetsIndex
    Case Is = 1 

        For Each wsBEIndex In Workbooks(desWBtoModify).Worksheets

            Select Case wsBEIndex.Name
                Case wsBEIndex.Name Like "* BE Consol"
                    wsBEIndex.Name = BEInputAns & " BE Consol"
                Case wsBEIndex.Name Like "* BE"
                    wsBEIndex.Name = BEInputAns & " BE"
                Case wsBEIndex.Name Like "* BE input tab"
                    wsBEIndex.Name = BEInputAns & " BE input tab"
                Case wsBEIndex.Name Like "Forecast* BE*"
                    wsBEIndex.Name = "Forecast " & BEInputAns & " BE"
            End Select

        Next wsBEIndex

    Case 2 To sheetsNeeded  

        'More codes here
    Case Else   'Delete Sheets
        'Codes to delete sheets
End Select

Next myforecastSheetsIndex

1 个答案:

答案 0 :(得分:1)

您的Select Case语句等同于以下If Then Else语句

        If wsBEIndex.Name = (wsBEIndex.Name Like "* BE Consol") Then
            wsBEIndex.Name = BEInputAns & " BE Consol"
        ElseIf wsBEIndex.Name = (wsBEIndex.Name Like "* BE") Then
            wsBEIndex.Name = BEInputAns & " BE"
        ElseIf wsBEIndex.Name = (wsBEIndex.Name Like "* BE input tab") Then
            wsBEIndex.Name = BEInputAns & " BE input tab"
        ElseIf wsBEIndex.Name = (wsBEIndex.Name Like "Forecast* BE*") Then
            wsBEIndex.Name = "Forecast " & BEInputAns & " BE"
        End If

如果查看该语句,您可以看到您正在使用True / False值测试wsBEIndex.Name是否相等,而工作表名称从不(或通常不是?)只是值True或False。

你实际上的陈述是

        If wsBEIndex.Name Like "* BE Consol" Then
            wsBEIndex.Name = BEInputAns & " BE Consol"
        ElseIf wsBEIndex.Name Like "* BE" Then
            wsBEIndex.Name = BEInputAns & " BE"
        ElseIf wsBEIndex.Name Like "* BE input tab" Then
            wsBEIndex.Name = BEInputAns & " BE input tab"
        ElseIf wsBEIndex.Name Like "Forecast* BE*" Then
            wsBEIndex.Name = "Forecast " & BEInputAns & " BE"
        End If

或作为Select Case语句

        Select Case True
            Case wsbeindex.Name Like "* BE Consol"
                wsbeindex.Name = BEInputAns & " BE Consol"
            Case wsbeindex.Name Like "* BE"
                wsbeindex.Name = BEInputAns & " BE"
            Case wsbeindex.Name Like "* BE input tab"
                wsbeindex.Name = BEInputAns & " BE input tab"
            Case wsbeindex.Name Like "Forecast* BE*"
                wsbeindex.Name = "Forecast " & BEInputAns & " BE"
        End Select