如何将用户过滤器应用于excel vba中的选择?

时间:2016-06-14 13:33:27

标签: excel vba excel-vba

我是vba的新手,我正在尝试创建一个简单的宏来将一些数据导出到文本文件中。我有这个工作,但是,当用户应用任何隐藏行的过滤器时,它只是将所有数据从第一行导出到最后一行,而忽略了过滤掉的任何内容。我已经搜遍过了,但是(可能是因为我缺乏vba的经验)我找不到任何适用于用户过滤器及其选择的东西。问题是,我甚至不知道过滤的行是否被excel视为“隐藏”。我还尝试了除下面列出的方法之外的许多方法,例如.AutoFilter和.SpecialCells(xlCellTypeVisible),但它们都不适用于Selection。

Sub old_export_for()
Dim myFile As String, rng As Range, cellValue As Variant, i As Integer, j As Integer
myFile = "C:\OUT\old_out_" + CStr(Format(Now(), "mmddhhmm")) + ".txt"
Set rng = Selection
Open myFile For Output As #1
For i = 1 To rng.Rows.Count
    If Not rng.Rows.Hidden Then
    j = 1
    cellValue = rng.Cells(i, j).Value
    Print #1, "Filename      : " + CStr(cellValue)
    j = 2
    cellValue = rng.Cells(i, j).Value
    Print #1, "File Size     : " + CStr(cellValue)
    j = 3
    cellValue = rng.Cells(i, j).Value
    Print #1, "Hostname      : " + CStr(cellValue)
    j = 4
    cellValue = rng.Cells(i, j).Value
    Print #1, "Date          : " + CStr(cellValue)
    j = 5
    cellValue = rng.Cells(i, j).Value
    Print #1, "Session ID    : " + CStr(cellValue),
    Print #1, vbNewLine + vbNewLine
    End If
Next i
Close #1
End Sub

3 个答案:

答案 0 :(得分:2)

更改

If Not rng.Rows.Hidden Then

If Not rng.Rows(i).EntireRow.Hidden Then

答案 1 :(得分:2)

只是为了展示我如何将其与SpecialCells

放在一起
Sub old_export_for()
  Dim myFile As String, rng As Range, cellValue As Variant, xRow As Variant
  myFile = "C:\OUT\old_out_" + CStr(Format(Now(), "mmddhhmm")) & ".txt"
  Set rng = Selection.SpecialCells(xlCellTypeVisible)
  Open myFile For Output As #1
    For Each xRow In rng.Rows
      Print #1, "Filename      : " & CStr(xRow.Cells(1).Value)
      Print #1, "File Size     : " & CStr(xRow.Cells(2).Value)
      Print #1, "Hostname      : " & CStr(xRow.Cells(3).Value)
      Print #1, "Date          : " & CStr(xRow.Cells(4).Value)
      Print #1, "Session ID    : " & CStr(xRow.Cells(5).Value)
      Print #1, vbNewLine & vbNewLine
    Next i
  Close #1
End Sub

仍然,对于这个简短的子句,我会使用像这样不可读的东西:

Sub old_export_for()
  Dim xRow As Variant, i As Long, str As String
  Open "C:\OUT\old_out_" + CStr(Format(Now(), "mmddhhmm")) & ".txt" For Output As #1
    For Each xRow In Selection.SpecialCells(xlCellTypeVisible).Rows: For i = 1 To 6
      Print #1, Array("Filename      : ", "File Size     : ", "Hostname      : ", "Date          : ", "Session ID    : ", vbNewLine)(i - 1) & Array(CStr(xRow.Cells(i).Value), vbNewLine)(1 + (i < 6))
    Next: Next
  Close #1
End Sub

但不要这样做:P

答案 2 :(得分:1)

如果这没用,我会删除答案。假设我们在 Sheet1 中有自动过滤的数据。这个小宏将获取标题行和所有可见数据行并将它们复制到 Sheet2

Sub AutoFilterCopyVisible()
    Sheets("Sheet1").AutoFilter.Range.Copy
    Sheets("Sheet2").Paste
End Sub

运行此功能后,您可以导出 Sheet2 。如果 Sheet1 如:

enter image description here

然后 Sheet2 将具有:

enter image description here

<强> 注意:

输出表中没有自动过滤。