types与工作表名称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 

我一直在“if sheets(x).name = …”行中获得types不匹配。 我不太熟悉Sheets.Names对象,我怎么搞这个types?

您的代码将正常工作。 只需要将If Sheets(x).Name =“MIR – Raw”或“MRR Raw”或“MWR Raw”或“PL Raw”或“SHP Raw”改为if(x)。 Name =“MIR – Raw”或Sheets(x).Name =“MRR – Raw”或Sheets(x).Name =“MWR – Raw”或Sheets(x).Name =“PL – Raw”或Sheets(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 

@ dee的答案已经解决了您的问题,但是由于我看到您正在检查太多的名称,因此我想为您的问题提供更优雅的解决scheme。

这个想法很简单:在两个单独的数组中转储“If”和“else if”的情况,并检查表单名是否在每个数组中,并采取相应的操作。 由于ElseIf子句中没有动作,所以我们可以用If/ElseIf来重写逻辑。 我在这个答案中使用了Jimmy Pena的函数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