我是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
答案 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)