过滤数据和复制值VBA

时间:2016-04-21 00:47:20

标签: excel vba excel-vba

我的代码应该过滤wsData中的数据,然后在A列中相互之后将其复制到wsTest工作表中。代码工作,除了它将值复制到目标工作表上的每个而不是相互之后。知道为什么吗?

Sub PrintReport()

Dim wbFeeReport As Workbook
Dim wsData As Worksheet
Dim wsForm As Worksheet
Dim wsTest As Worksheet
Dim FrRngCount As Range
Dim i As Integer
Dim k As Integer
Dim t As Integer
Dim s As Integer



Set wbFeeReport = Workbooks("FeExcForm.xlsm")

Set wsData = wbFeeReport.Worksheets("Data")
Set wsTest = wbFeeReport.Worksheets("Test")

wsTest.Cells.Clear

wsData.Activate


i = 1

For k = 1 To 2

With ActiveSheet
.AutoFilterMode = False
With Range("A1", Range("A" & Rows.Count).End(xlUp))
 .AutoFilter 1, k
   On Error Resume Next
    .SpecialCells(xlCellTypeVisible).Copy Destination:=wsTest.Range("A" & i)
End With
i = wsTest.Range("A" & Rows.Count).End(xlUp)
.AutoFilterMode = False
End With

Next k

End Sub

1 个答案:

答案 0 :(得分:1)

作为第一点:如果使用AutoFilter的范围,则copy将始终排除隐藏的单元格

With Range("A1", Range("A" & Rows.Count).End(xlUp))
  .AutoFilter 1, k
  .Copy wsTest.Range("A" & i)
End With

这就是你所需要的 关于您的错误:On Error Resume Next隐藏i = wsTest.Range("A" & Rows.Count).End(xlUp)的错误,该错误将返回范围而不是数值。

i = wsTest.Range("A" & Rows.Count).End(xlUp).Row + 1

是你的朋友:)

一起看起来应该是这样的:

Sub PrintReport()

  Dim wbFeeReport As Workbook
  Dim wsData As Worksheet
  Dim wsForm As Worksheet
  Dim wsTest As Worksheet
  Dim FrRngCount As Range
  Dim i As Integer
  Dim k As Integer
  Dim t As Integer
  Dim s As Integer

  Set wbFeeReport = Workbooks("FeExcForm.xlsm")

  Set wsData = wbFeeReport.Worksheets("Data")
  Set wsTest = wbFeeReport.Worksheets("Test")

  wsTest.Cells.Clear
  wsData.Activate

  i = 1

  For k = 1 To 2
    With wsData
      .AutoFilterMode = False

      With .Range("A1", Range("A" & Rows.Count).End(xlUp))
        .AutoFilter 1, k
        .Copy wsTest.Range("A" & i)
      End With

      i = wsTest.Range("A" & Rows.Count).End(xlUp).Row + 1
      .AutoFilterMode = False
    End With
  Next k

End Sub

编辑:要排除标题,只需更改:

.Copy wsTest.Range("A" & i)

为:

If i = 1 Then .Copy wsTest.Range("A" & i) Else .Offset(1, 0).Copy wsTest.Range("A" & i)

如果您根本不需要任何标题,请直接使用:

.Offset(1, 0).Copy wsTest.Range("A" & i)

但我没有测试过它。如果你遇到任何问题,请告诉我;)