问题
I am trying to get a selection from a worksheet in Excel using VBA, to use this selection as input for a next step of analysis on the data. This works fine, until you make a selection that has filtered rows in between. In that case it will only get the part of the range that is before the filtered rows.
How can I also get the selected row(s) after the filtered rows?
Below is the code that I use for getting the selected rows from the sheet, and an example of a selection where the code does not work as intended.
For Each area In Selection.Areas
Set newRange = area
Set rnge = Selection.SpecialCells(xlCellTypeVisible)
For i = 1 To rnge.Rows.Count
x = rnge.Cells(i, 5).Value
y = rnge.Cells(i, 6).Value
Write #1, x, y
Next i
Next
Update: using the code below, I got it to work, thanks to SNicolaou's answer
Set rnge = Selection.SpecialCells(xlCellTypeVisible)
For Each area In rnge.Areas
For i = 1 To area.Rows.Count
x = area.Cells(i, 5).Value
y = area.Cells(i, 6).Value
Write #1, x, y
Next i
Next
回答1:
There are two approaches to how to select the cells: for example, holding the shift key and clicking individually on two cells then you have two areas in your selection. holding the shift key and click and drag to select the two cells will create one area. ie. if my cells are A1 and B1 then in the first case i will get two areas "$A$1","$B$1" whereas in the second case you will get one area "$A$1:$B$1"
So if you want to go for one selection then you will need to split the selection as below:
Private Sub sTestSolution()
Dim area As Range, newRange As Range
Dim i As Long, x As Variant, y As Variant
Set newRange = Selection.SpecialCells(xlCellTypeVisible)
For Each area In newRange.Areas
Debug.Print area.Address
Next
End Sub
If you want to go for multiple selection then the code will be like this (adjust accordingly):
Private Sub sTestSolution()
Dim area As Range
Dim i As Long, x As Variant, y As Variant
For Each area In Selection.Areas
For i = 1 To area.Rows.Count
x = area.Cells(i, 1).Value
y = area.Cells(i, 2).Value
Debug.Print area.Address
Next i
Next
End Sub
Following up on your comment, i get the below when i have selected those rows in my screenshot.
来源:https://stackoverflow.com/questions/58197316/how-to-get-full-selection-from-excel-sheet-using-vba-without-the-filtered-rows-t