简体   繁体   中英

Range(cells).visiblecells selecting the whole sheet

I'm using variable references for selecting a filtered range in a loop and having some hard time when the range references become same. When it becomes same the code is selecting the whole sheet. I'm unable to solve this. Here's my code

For tor = 11 To 17 ' for selecting the column
  .UsedRange.AutoFilter Field:=tor, Criteria1:="Yes"
  coot = .Cells(.Rows.Count, 1).End(xlUp).Row
  If coot > 1 Then ' stuck here when coot becomes 2 code is selecting the whole sheet
  Set yesrng = .Range(Cells(2, tor), Cells(coot,tor)).SpecialCells(xlCellTypeVisible)
  yesrng.Select
  end if
Next tor

If row value is 2 在此处输入图片说明 if row value is anything other than 2 在此处输入图片说明

If you try to apply SpecialCells(xlCellTypeVisible) to a single cell that is not visible it just takes the whole sheet. You could check if your range is single cell:

Dim wholeRng As Range
Set wholeRng = .Range(Cells(2, tor), Cells(coot,tor))
If wholeRng.Cells.Count = 1 Then
    If wholeRng.EntireRow.Hidden = True Then
        Set yesrng = Nothing
    Else
        Set yesrng = wholeRng
    End If
Else
    Set yesrng = wholeRng.SpecialCells(xlCellTypeVisible)
End If

However you also run into a problem if you apply SpecialCells to a multi cell range that has no visible cells (you'll get an error 1004 something like "No cells were found"). You can use an error handler (or just ignore the error)

'...
Set yesrng = Nothing 'so you'll know if it worked
On Error Resume Next 'ignore errors
Set yesrng = wholeRng.SpecialCells(xlCellTypeVisible)
On Error Goto 0 'reactivate default error handling!
'...

Then always check If yesrng Is Nothing afterwards! The nicer way would be to check the error number but since 1004 is a pretty generic error it wouldn't help much.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM