在Them,VBA中复制/粘贴具有特定字符串名称的单元格的问题

时间:2016-04-08 14:05:05

标签: excel vba excel-vba

我正在使用此代码检查工作表中的每一行" Report2"对于短语" Chicago"并使用" Chicago"复制并粘贴任何行。在他们的新表。但是,它不起作用。任何有关为什么会受到赞赏的帮助。

Sub BranchCount()

Dim s As Worksheet
Dim LastRow As Long

Set s = Worksheets("Report 1")
LastRow = s.UsedRange.SpecialCells(xlCellTypeLastCell).Row

Worksheets("Report 1").Select
Range("A1:J" & LastRow).Select
Selection.Copy

Sheets.Add.Name = "Report2"
Selection.PasteSpecial xlPasteValues
Range("A1").EntireRow.Delete
Range("B1").EntireRow.Delete
Range("C1").EntireRow.Delete

Dim Z As Range
Dim Y As String

Y = "Chicago"

Dim Q As Worksheet
Dim LastRow2 As Long

Set Q = Worksheets("Report2")
LastRow2 = Q.UsedRange.SpecialCells(xlCellTypeLastCell).Row

Sheets("Report2").Range("A1").Select

For Each Z In Range("J1:J" & LastRow2)
    If Y = Z.Value Then
        Z.EntireRow.Copy
            Sheets("Clean").Select
                Range("A500").End(xlUp).Offset(1, 0).Select
                Selection.PasteSpecial xlPasteValues
            Sheets("Report2").Select
    End If
Next

End Sub

我使用Excel 2013.如果您能提供帮助,请与我们联系。谢谢!

1 个答案:

答案 0 :(得分:0)

我尝试使用工作表变量进行清理。您开始使用它们,但应该在任何地方实现它们(再次,请参阅我的评论中的链接)。

我想我了解你的数据在哪里,但你可能需要调整以下内容(使用 F8 一次一行):

Sub BranchCount()
Dim rptOneWS As Worksheet, rptTwoWS As Worksheet
Dim s As Worksheet
Dim LastRow As Long

Set rptOneWS = Worksheets("Report 1")
Set rptTwoWS = Sheets.Add
rptTwoWS.Name = "Report 2"

LastRow = rptOneWS.UsedRange.SpecialCells(xlCellTypeLastCell).Row

'If you just want values, set two ranges equal. That way you
' skip using the clipboard
rptTwoWS.Range("A1:J" & LastRow).Value = rptOneWS.Range("A1:J" & LastRow).Value
With rptTwoWS
    .Range(.Rows(1), .Rows(3)).EntireRow.Delete
End With

Dim Z As Range
Dim Y As String

Y = "Chicago"

Dim LastRow2 As Long

LastRow2 = rptTwoWS.UsedRange.SpecialCells(xlCellTypeLastCell).Row

For Each Z In rptTwoWS.Range("J1:J" & LastRow2)
    If Y = Z.Value Then
        Z.EntireRow.Copy
            Sheets("Clean").Range("A500").End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
    End If
Next

End Sub