for循环有一个运行时错误91

时间:2017-08-03 10:54:36

标签: excel-vba vba excel

for循环有运行时错误91需要帮助!!

Sub clearSheet(WSName As String)

    Dim ws As Worksheet
    Set ws = Nothing

    With ActiveWorkbook
        Dim blWSExists As Boolean
        blWSExists = False
        For i = 1 To .Sheets.Count
            If .Sheets(i).Name = WSName Then
                blWSExists = True
                .Sheets(i).Activate
                .Sheets(i).Visible = xlSheetVisible
            End If
        Next
        If Not blWSExists Then
            Set ws = .Sheets.Add
            ws.Move after:=.Sheets(.Sheets.Count)
            ws.Name = WSName
            ws.Visible = xlSheetVisible
        End If
        .Sheets(WSName).AutoFilterMode = False
        .Sheets(WSName).Cells.Clear
        .Sheets(WSName).UsedRange.ClearOutline
        .Sheets(WSName).Cells.ClearFormats
    End With

End Sub

2 个答案:

答案 0 :(得分:0)

试试:

Dim ws As Worksheet
Dim blWSExists As Boolean

blWSExists = False

For Each ws In Worksheets
    If ws.Name = WSName Then
        blWSExists = True
    End If
Next

If Not blWSExists Then
    ActiveWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count)
    ActiveSheet.Name = WSName
End If

Set ws = ActiveWorkbook.Sheets(WSName)

ws.AutoFilterMode = False
ws.Cells.Clear
ws.UsedRange.ClearOutline
ws.Cells.ClearFormats
ws.Activate

答案 1 :(得分:0)

您可以使用Cells.Delete()清除工作表上的所有内容:

Sub clearSheet(WSName As String)

    Dim s As Object

    For Each s in ThisWorkbook.Sheets  
        If s.Name = WSName Then
            s.Visible = xlSheetVisible
            If TypeOf s Is worksheet Then s.Cells.Delete    ' not all Sheets have cells, but all Worksheets do
            Exit Sub                                        ' to ignore the rest of the code if the Sheet exists
        End If
    Next

    ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)).Name = WSName

End Sub

或者只是删除工作表并添加新工具以清除与工作表相关的所有内容:

Sub clearSheet(WSName As String)
    On Error Resume Next
    Sheets(WSName).Delete
    Sheets.Add(After:=Sheets(Sheets.Count)).Name = WSName 
End Sub