如何将用户filter应用于excel vba中的select?

我是新来的vba,并试图创build一个简单的macros来将一些数据导出到一个文本文件。 但是,我有这个工作,当用户应用任何隐藏行的filter,它只是简单地将第一行的所有数据导出到最后一行,忽略任何过滤掉的东西。 我已经搜遍了所有,但(可能从我缺乏经验的vba)我无法find任何将与用户的filter和他们的select一起工作的任何东西。 问题是,我甚至不知道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 

更改

 If Not rng.Rows.Hidden Then 

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

只是为了展示我将如何与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

如果这没有帮助,我会删除答案。 假设我们在Sheet1中有AutoFiltered数据。 这个微小的macros将采取标题行和所有可见的数据行,并将其复制到Sheet2

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

运行后,可以导出Sheet2 。 如果Sheet1如下所示:

在这里输入图像说明

那么Sheet2将有:

在这里输入图像说明

注意:

输出表中没有自动过滤。