Excel VBA查找行,复制内容,粘贴在下一张工作表中,然后删除原始数据

时间:2018-09-04 04:23:48

标签: excel vba excel-vba

我正在努力确定工作表1中的行,这些行在A列中不是空白并且在V列中没有Y或L。然后,我需要复制该行的内容,然后将值粘贴到打开的行中在下一个工作表上的行。最后,我需要清除该行原始工作表中的内容。粘贴时间到了,我被卡住了。错误1004-对象“ _Worksheet”的方法“范围”失败。感谢您的帮助。

Option Explicit
Option Compare Text
Sub EndMove()

Dim rowCount As Long, i As Long
Dim ws As Worksheet: Set ws = ActiveSheet
ws.Range("A11").Select
rowCount = ws.Cells(ws.Rows.Count, 1).End(xlUp).row
Application.ScreenUpdating = False: Application.EnableEvents = False
Call ShowAllRecords
For i = 11 To rowCount
    If ws.Range("V" & i) <> "y" And ws.Range("V" & i) <> "l" Then
        If ws.Range("A" & i) <> "" Then

Dim rowCount2 As Long, j As Long
Dim sRng As Range
Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Sheets(ActiveSheet.Index + 1)
Dim wAct As Worksheet
Dim lRow As Long
Dim End_Row As Long

Set wAct = ws
Set sRng = ws.Range("V" & i)

If Not IsDate("01 " & wAct.Name & " 2017") Or wAct.Name = "Dec" Then MsgBox "Not applicable for this sheet.": Exit Sub
If ActiveSheet.Index = ThisWorkbook.Worksheets.Count Then MsgBox "This is the last worksheet cannot move forward.": Exit Sub


wAct.unprotect

With ws2
    .unprotect

If rowCount2 = "1" Then

        For j = 11 To Rows.Count
        If .Range("A" & j) = "" Then
            End_Row = j
            Exit For
        End If
    Next j
Else

End If
    wAct.Range("A" & sRng.row & ":AD" & sRng.row + sRng.Rows.Count - 1).Copy
    .Range("A" & End_Row).PasteSpecial xlPasteValuesAndNumberFormats
    wAct.Range("A" & sRng.row & ":AD" & sRng.row + sRng.Rows.Count - 1).ClearContents
    .Range("A1000").Value = End_Row
    .protect DrawingObjects:=True, Contents:=True, Scenarios:=True, AllowFiltering:=True
End With

wAct.protect DrawingObjects:=True, Contents:=True, Scenarios:=True, AllowFiltering:=True

Application.CutCopyMode = False


        End If
      End If
Next i
Application.EnableEvents = True: Application.ScreenUpdating = True
Call FilterBlanks
MsgBox "Move Complete"
End If
End Sub

1 个答案:

答案 0 :(得分:1)

似乎您的代码中没有行可以为rowCount2赋值。因此,当您在下面的代码中对其进行检查时,它始终为false,因此跳过了这一部分

If rowCount2 = "1" Then

        For j = 11 To Rows.Count
        If .Range("A" & j) = "" Then
            End_Row = j
            Exit For
        End If
    Next j
Else

但这部分是必不可少的,因为它是End_Row被分配值的唯一部分。因此,当您尝试.Range("A" & End_Row)执行此操作时,End_Row中没有任何内容。在该行上设置一个断点,并检查End_Row的Locals屏幕以确保它是此行。