2014-02-11 140 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 
相关问题