2017-08-03 96 views
1

循環中存在運行時錯誤91需要幫助!循環中存在運行時錯誤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 
+0

tr y顛倒2行的順序,首先使它可見'.Sheets(i).Visible = xlSheetVisible',然後激活它'.Sheets(i).Activate' –

+0

nop沒有工作 –

+2

也許它沒有,但無論如何,你需要切換它們。你在哪一行得到這個錯誤? –

回答

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 
+0

這條線上有運行時錯誤1004 :(「For Each ws In Worksheets」 –

+0

@HA嘗試在For循環之前放置'Set ws = Nothing'這個錯誤在這裏沒有發生。 –

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