如何选择过滤表的第一个和最后一个单元格?

时间:2017-09-15 21:57:12

标签: excel vba excel-vba

下面的代码是去动物进入的桌子和过滤器。动物选择是狗,猫和仓鼠。然后拉出日期和时间并将其粘贴在另一张纸上。

我的问题与随机数量的狗可以出现在任何一天让我们说37出现。

我可以正确地提取数据,但是当我去拉猫时,它从第38行开始,我的代码继续从第2行拉出来。

无论选择什么动物,如何选择过滤表的第一个和最后一个单元格,如何让我的代码从右侧开始?

Sub VetDate()
str = ""
str2 = ""
 With Sheet1
  .AutoFilterMode = False
   With .Range("A1:N1")
    .AutoFilter
    .AutoFilter Field:=9, Criteria1:="dog"
    str = .Range("A2").Value 'How to fix this part
    str2 = .Range("A1").End(xlDown).Value 'How to fix this part
    End With
  End With
  With Sheet2
   .Range("D36:D37").ClearContents
   .Range("D36").Value = Format(str, "mmm-dd-yy hh:mm am/pm")
   .Range("D37").Value = Format(str2, "mmm-dd-yy hh:mm am/pm")
   .Range("D36:D37").HorizontalAlignment = xlCenter
 End With
End Sub

1 个答案:

答案 0 :(得分:2)

请试试这个:

Sub VetDate()

Dim StrRow As Long
Dim Str2Row As Long

str = ""
str2 = ""
 With Sheet1
  .AutoFilterMode = False
   With .Range("A1:N1")
    .AutoFilter
    .AutoFilter Field:=9, Criteria1:="dog"
    StrRow = Activesheet.AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 2).Row
    Str2Row = Range("A" & Rows.Count).End(xlUp).Row
    str = .Range("A" & Str2Row).Value 'How to fix this part
    str2 = .Range("A" & StrRow).Value 'How to fix this part
    End With
  End With
  With Sheet2
   .Range("D36:D37").ClearContents
   .Range("D36").Value = Format(str, "mmm-dd-yy hh:mm am/pm")
   .Range("D37").Value = Format(str2, "mmm-dd-yy hh:mm am/pm")
   .Range("D36:D37").HorizontalAlignment = xlCenter
 End With
End Sub

希望这个帮助