范围(单元格).visiblecells选择整个工作表

时间:2016-09-16 07:19:37

标签: vba excel-vba excel

我使用变量引用来选择循环中的过滤范围,并且在范围引用变得相同时有一些困难时间。当它变得相同时,代码选择整张纸。我无法解决这个问题。 这是我的代码

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

如果行值为2 enter image description here 如果行值不是2 enter image description here

1 个答案:

答案 0 :(得分:2)

如果您尝试将SpecialCells(xlCellTypeVisible)应用于不可见的单个单元格,则只需要整张表单。您可以检查您的范围是否是单个单元格:

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

但是,如果将SpecialCells应用于没有可见单元格的多单元格区域,则会遇到问题(您将收到错误1004,例如“找不到单元格”)。您可以使用错误处理程序(或只是忽略错误)

'...
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!
'...

然后总是检查If yesrng Is Nothing!更好的方法是检查错误号,但由于1004是一个非常普通的错误,所以没有多大帮助。

相关问题