使用工作表名称VBA键入不匹配

时间:2014-05-03 22:53:07

标签: excel vba excel-vba

我试图编写一个运行在工作簿中的简单VBA代码,删除一些完整的工作表,并清除其他工作表的内容。这是我的代码:

Sub CleanSheets()
Dim x As Integer

x = 1
Do Until x = Sheets.Count
    If Sheets(x).Name = "MIR - Raw" Or "MRR - Raw" Or "MWR - Raw" Or "PL - Raw" Or "SHP - Raw" Then
    'clear them
        Sheets(x).ClearContents
    ElseIf Sheets(x).Name = "Dashboard" Then

    Else
        'delete the sheet
        Application.DisplayAlerts = False
        Sheets(x).Delete
        Application.DisplayAlerts = True
        x = x - 1
    End If
x = x + 1
Loop
End Sub

我继续在"如果sheet(x).name = ..."上出现类型不匹配的问题。线。我对Sheets.Names对象不太熟悉,我怎么搞砸这个类型?

2 个答案:

答案 0 :(得分:2)

@ dee的答案已经解决了你的问题,但是我看到你检查的名字太多了,我想为你的问题提供一个更优雅的解决方案。

这个想法非常简单:将“If”和“else if”情况转储到两个单独的数组中,并检查工作表名称是否在每个数组中,并采取相应的操作。由于ElseIf子句中没有操作,我们只能用If/ElseIf重写逻辑。我使用Jimmy Pena's中的this answer函数IsInArray进行检查。

此外,我在代码中做了一些更改,以使其更具可读性:

Sub CleanSheets()
    Dim x As Long   ' Long is safer and faster
    Dim aFirstCategory(4) As String
    Dim aSecondCategory(1) As String

    ' Note that checking for the sheet name is usually not very robust.
    ' You might be interested in the Like function to make your checks more flexible
    aFirstCategory(0) = "MIR - Raw"
    aFirstCategory(1) = "MRR - Raw"
    aFirstCategory(2) = "MWR - Raw"
    aFirstCategory(3) = "PL - Raw"
    aFirstCategory(4) = "SHP - Raw"

    aSecondCategory(0) = "Dahshboard"

    x = 1  ' I would check with ForEach wSheet in Sheets instead
    Do 'Until should go to the end of the loop, else the last sheet will not be checked
        If IsInArray(Sheets(x).Name, aFirstCategory) Then
        'clear them
            Sheets(x).Cells.ClearContents ' Sheets(x).ClearContents gives error I think
        ElseIf not IsInArray(Sheets(x).Name, aSecondCategory) Then
            'delete the sheet
            Application.DisplayAlerts = False
            Sheets(x).Delete
            Application.DisplayAlerts = True
            x = x - 1
        End If
        x = x + 1
    Loop Until x = Sheets.Count
End Sub

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
  IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function

答案 1 :(得分:1)

您的代码可以正常运行。只需要更改If Sheets(x).Name =" MIR - Raw"或者" MRR - Raw"或者" MWR - Raw"或者" PL - Raw"或者" SHP - Raw" 如果Sheets(x).Name =" MIR - Raw"或表格(x).Name =" MRR - Raw"或表格(x).Name =" MWR - Raw"或表格(x).Name =" PL - Raw"或表格(x).Name =" SHP - Raw"

Sub CleanSheets()
Dim x As Integer

x = 1
Do Until x = Sheets.Count
    If Sheets(x).Name = "MIR - Raw" Or Sheets(x).Name = "MRR - Raw" Or Sheets(x).Name = "MWR - Raw" Or Sheets(x).Name = "PL - Raw" Or Sheets(x).Name = "SHP - Raw" Then
    'clear them
        Sheets(x).ClearContents
    ElseIf Sheets(x).Name = "Dashboard" Then

    Else
        'delete the sheet
        Application.DisplayAlerts = False
        Sheets(x).Delete
        Application.DisplayAlerts = True
        x = x - 1
    End If
x = x + 1
Loop
End Sub