简体   繁体   English

Range(cells).visiblecells选择整个工作表

[英]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 如果行值为2 在此处输入图片说明 if row value is anything other than 2 如果行值不是2 在此处输入图片说明

If you try to apply SpecialCells(xlCellTypeVisible) to a single cell that is not visible it just takes the whole sheet. 如果您尝试将SpecialCells(xlCellTypeVisible)应用于不可见的单个单元格,则只需整张纸即可。 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"). 但是,如果将SpecialCells应用于没有可见单元格的多单元格区域,也会遇到问题(错误1004,例如“找不到单元格”)。 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! 然后,请始终检查“ If yesrng Is Nothing之后是否If yesrng Is Nothing The nicer way would be to check the error number but since 1004 is a pretty generic error it wouldn't help much. 更好的方法是检查错误号,但是由于1004是一个非常普通的错误,因此不会有太大帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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