过滤并将数据移动到不同的工作表问题

时间:2015-06-08 12:35:38

标签: excel vba excel-vba

我的代码的目标是通过“状态已更改”字符串从工作表“数据”过滤列ABC复制数据,然后将此列和此ABC列右侧的后6列复制到工作表“解析” 这里的问题是,有时ABC在第1列,有时在第2列。所以下面的代码不起作用:/因为只看第1列

非常感谢。

Sub Filter_and_move_data()
Dim LastRow As Long

With Worksheets("data")
    .Range("$A:$J").AutoFilter
    .Range("$A:$G").AutoFilter field:=1, Criteria1:="Status Changed"
    LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
    .Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
            Destination:=Sheets("parsing").Range("A1")
End With
End Sub

3 个答案:

答案 0 :(得分:0)

这样做;)

Sub Filter_and_move_data()

With Worksheets("data")
    .Range("$A:$J").AutoFilter
    .Range("$A:$G").AutoFilter field:=1, Criteria1:="Status Changed"
    .AutoFilter.Range.Copy _
            Destination:=Sheets("parsing").Range("A1")
End With
End Sub

答案 1 :(得分:0)

要仅复制行A-G中的数据而不是整行更改此行

.Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
            Destination:=Sheets("parsing").Range("A1")

进入这个:

 .Range("A1:G" & LastRow).SpecialCells(xlCellTypeVisible).Copy _
            Destination:=Sheets("parsing").Range("A1")

答案 2 :(得分:0)

如果您不知道ABC列的起始位置,您有两种选择:要么在函数中检测列abc的范围,要么将此范围作为参数传递。然后,您必须为自动过滤器设置正确的字段(如果需要,您也可以更正范围) 之后,您不需要像实际那样复制整行,而只需要复制下六列。因此,您必须确定要复制的范围,具体取决于您为ABC列找到的范围 以下是第一个解决方案的代码:

Sub Filter_and_move_data()
Dim LastRow As Long
Dim aCell As Range
Dim columnsToCopy As Long
columnsToCopy = 6
'determine where is located column abc between columns a and b (or whatever other range you need)
With Worksheets("data").Range("a1:b1")
    Set aCell = .Find("ABC", LookIn:=xlValues)
    Debug.Print aCell.Address & " // " & aCell.Column
End With

With Worksheets("data")
    .Range("$A:$G").AutoFilter field:=aCell.Column, Criteria1:="Status Changed"
    LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
    .Range(Cells(1, aCell.Column), Cells(LastRow, aCell.Column + columnsToCopy)).SpecialCells(xlCellTypeVisible).Copy _
            Destination:=Sheets("parsing").Range("A1")
End With  
End Sub
相关问题