2016-09-16 76 views
-1

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

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

+0

你能提供一张工作表的快照吗?这将有助于理解这个问题更多 – Zac

+0

@Zac图片按照请求添加。 – Neelesh

+0

顶部有隐藏的行吗? – Zac

回答

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是一个非常普遍的错误,所以没有多大帮助。

+0

不知道的行数。感谢您的解释 – Zac

+0

@arcadeprecinct细胞是可见的,请检查现在添加的图像。我只想选择K2:K2.visible cells之间的范围。原因是我使用的循环与5列相同。问题仅在行值变为2时出现。如果行值不是2,则代码按预期工作。 – Neelesh

+0

如果行值为2,则范围只有一个单元格。当我测试它时,只有当这个单元被隐藏时,问题才出现,但我可能是错的。独立处理一个细胞的特殊情况应该仍然有效? – arcadeprecinct