【问题标题】:filter and return row, first row always get returned, vba过滤并返回行,第一行总是返回,vba
【发布时间】:2015-02-03 05:29:53
【问题描述】:

我有一个组合框,其中包含我想在另一个工作簿列中搜索的值。然后使用自动过滤器的代码返回在同一列(第 4 列)中具有该值的行。 它工作正常,但是源的第一行总是被复制到目标,天气它有或没有在特定列中寻找的值。 偏移量或单元格移位被用作两张表中的前两行是标题

Sub CommandButton1_Click()
'Look in data repository for the Combobox filter value and only return those associated rows (can be more than one)

Dim DataBlock As Range, Dest As Range
Dim LastRow As Long, LastCol As Long
Dim SheetOne As Worksheet, SheetTwo As Worksheet
Dim PN As String
PN = ComboBox1.Value

'set references up-front
Set SheetTwo = ThisWorkbook.Worksheets("Report") 'this is the expiditing report
Set SheetOne = Workbooks.Open("C:\Users\Colin\Documents\Nexen\Data Repository V1.xlsm").Sheets("Data") 'this is the expiditing report
Set Dest = SheetTwo.Cells(3, 1) '<~ this is where we'll put the filtered data

'identify the "data block" range, which is where
'the rectangle of information that Ill apply
'.autofilter to
With SheetOne
    LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
    LastCol = .Cells(2, .Columns.Count).End(xlToLeft).Column
    Set DataBlock = .Range(.Cells(3, 1), .Cells(LastRow, LastCol))
    'Set DataBlock = Range("A3:AV65000") 'for testing
End With

'apply the autofilter to column D (i.e. column 4)
With DataBlock
    'can use offset .Offset(2, 0).
    .AutoFilter Field:=4, Criteria1:=PN
    'copy the still-visible cells to sheet 2
    .SpecialCells(xlCellTypeVisible).Copy Destination:=Dest
End With

'turn off the autofilter
With SheetOne
    .AutoFilterMode = False
    If .FilterMode = True Then .ShowAllData
End With

End Sub

Sub CommandButton2_Click()

Dim MyBook As String
Dim MyRange As Range
    'Get name of current wb
    MyBook = ThisWorkbook.Name
  Set MyRange = MyBook.Sheets("Report").Range("T3,AC65000")

'ActiveWorkbook.Close savechanges:=True
 MyBook.Activate


End Sub

![etr][1]

那么,为什么我无论如何都要拿回第一行呢?我尝试了很多方法。

【问题讨论】:

  • .Offset(1, 0).Resize(LastRow - 1, LastCol).SpecialCells(xlCellTypeVisible).Copy Destination:=Dest
  • 在复制时尝试使用.CurrentRegion,例如With DataBlock (...).CurrentRegion.Copy Dest,根据我的经验,在这种情况下比.SpecialCells 好得多。

标签: vba excel filter copying


【解决方案1】:

您的.Range 需要位于Table 中,并带有AutoFilter 的标头才能正常工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多