2014-02-11 139 views
1

當我開始新的分離時,我想刪除特定工作表之間的舊數據。 (在綠色&紅色之間)。不幸的是,我得到這個錯誤信息,無法弄清楚我做錯了什麼。錯誤1004範圍類別的刪除方法失敗

「錯誤1004 Range類的刪除方法失敗「

請幫助! 謝謝。

'----------------------------- 
Sub Test() 
'----------------------------- 
    Dim ws As Worksheet 
    Dim lRow As Long, lCol As Long 
    Dim Rng As Range 
    Dim beginIdx As Integer, endIdx As Integer 

    '-- Get the 'Green' and 'Red' indexses in the active workbook . 
    beginIdx = ActiveWorkbook.Sheets("Green").Index + 1 
    endIdx = ActiveWorkbook.Sheets("Red").Index - 1 

    '-- Delete old data between 'Green' and 'Red' tabs 
    For J = beginIdx To endIdx 

     '-- Set this to the relevant worksheet 
     Set ws = ActiveWorkbook.Sheets(J) 

     With ws 
       '-- Get the last row and last column 
       lRow = .UsedRange.SpecialCells(xlCellTypeLastCell).row 
       lCol = .Cells(1, .Columns.Count).End(xlToLeft).Column 

       '-- Set the sheet range to delete old data leaving the headings intact 
       Set Rng = .Range(.Cells(2, 1), .Cells(lRow, lCol)) 

       Application.DisplayAlerts = False ' Get rid of pop-up message 

       With Rng 
        '-- Now delete the old data from the sheet 
        .EntireRow.Delete 
       End With 

       Application.DisplayAlerts = True ' Back to normal 
     End With 

    Next J 

End Sub 
+0

調試時 –

+0

lRow = 2,lCol = 38 – Hycinth

+0

它爲me..can您展示您的工作簿(使用HTTPS例如,什麼樣的價值觀在'lRow'和'lCol'://www.dropbox .com)? –

回答

1

此工作現在。我只需要包括:
*如果檢查lRow值的語句是> 2
*將範圍單元格值從2增加到3(Set Rng = .Range(.Cells(3,1)...)

'----------------------------- 
Sub Test() 
'----------------------------- 
    Dim ws As Worksheet 
    Dim lRow As Long, lCol As Long 
    Dim Rng As Range 
    Dim beginIdx As Integer, endIdx As Integer 

    '-- Get the 'Green' and 'Red' indexses in the active workbook . 
    beginIdx = ActiveWorkbook.Sheets("Green").Index + 1 
    endIdx = ActiveWorkbook.Sheets("Red").Index - 1 

    '-- Delete old data between 'Green' and 'Red' tabs 
    For J = beginIdx To endIdx 

     '-- Set this to the relevant worksheet 
     Set ws = ActiveWorkbook.Sheets(J) 

     With ws 
       '-- Get the last row and last column 
       lRow = .UsedRange.SpecialCells(xlCellTypeLastCell).row 
       lCol = .Cells(1, .Columns.Count).End(xlToLeft).Column 

       '-- Set the sheet range to delete old data leaving the headings intact 
       If lRow > 2 Then 
        Set Rng = .Range(.Cells(3, 1), .Cells(lRow, lCol)) 

        Application.DisplayAlerts = False ' Get rid of pop-up message 

        With Rng 
         '-- Now delete the old data from the sheet 
         .EntireRow.Delete 
        End With 
      End If 

       Application.DisplayAlerts = True ' Back to normal 
     End With 

    Next J 

End Sub 
相關問題