![](/img/trans.png)
[英]Selecting Visible Cells is not working although using `SpecialCells(xlCellTypeVisible)`
[英]range in sheet.SpecialCells(xlCellTypeVisible) also selecting blank rows although a filter was applied VBA
我正在嘗試循環一個工作表中的所有非隱藏和非空白行。 問題是,它確實循環通過非隱藏,但當它到達非隱藏表的末尾時,它就會永遠地繼續前進。
我知道它在過濾器后檢索了147行(包括隱藏的行),並且在執行循環時它確實跳過了它們,但是在完成147之后,它繼續到148,依此類推,我有一個驗證來檢查它是否檢索到空白,它停在那里。 我希望它停在147或任何數量的行拋出過濾器。
我在做什么:
'I need the cells in B1 to begin with 0 or W, I guess I'd have to add a non-blank option (see below)
With MaterialListSheet
.AutoFilterMode = False
.Range("B1").AutoFilter Field:=1, Criteria1:="0*", Operator:=xlOr, Criteria2:="W*"
End With
Set rangeMaterialList = MaterialListSheet.Range("B2:B" & Rows.Count)
For Each CellML In rangeMaterialList.SpecialCells(xlCellTypeVisible)
'Reset the variable in order to avoid unwanted codes
BomCodesToSplit = ""
'Check if there's a code in the cell
If MaterialListSheet.Range("C" & CellML.Row & ":C" & CellML.Row).Value <> "" Then
BomCodesToSplit = MaterialListSheet.Range("C" & CellML.Row & ":C" & CellML.Row).Value
End If
'Check if theres a code in the cell AND if it does concatenate (in case the variable isn't empty)
If MaterialListSheet.Range("D" & CellML.Row & ":D" & CellML.Row).Value <> "" Then
If BomCodesToSplit <> "" Then
BomCodesToSplit = BomCodesToSplit & " / " & MaterialListSheet.Range("D" & CellML.Row & ":D" & CellML.Row).Value
Else
BomCodesToSplit = MaterialListSheet.Range("D" & CellML.Row & ":D" & CellML.Row).Value
End If
End If
'Check if any BomCodes were retrieved
If BomCodesToSplit = "" Then
MsgBox "There was an error getting the Bom Codes", vbCritical, "Execution Terminated"
End
Else
BomCodes = Split(BomCodesToSplit, "/")
End If
Next CellML
End Sub
我試過的過濾器:
'Im aware this doesn't work but decided to try it anyway
With MaterialListSheet
.AutoFilterMode = False
.Range("B1").AutoFilter Field:=1, Criteria1:="<>"
.Range("B1").AutoFilter Field:=1, Criteria1:="0*", Operator:=xlOr, Criteria2:="W*"
End With
'我也意識到這是不可能的(我認為)
With MaterialListSheet
.AutoFilterMode = False
.Range("B1").AutoFilter Field:=1, Criteria1:="0*", Operator:=xlOr, Criteria2:="W*", Operator:=xlAnd, Criteria3:="<>"
End With
我甚至不知道這是一個過濾器,還是我錯過了什么? 我是VBA的新手,還有很多我還不知道的事情。 我想要的只是循環直到(在這種情況下為147,因此它不會進入'Check if any BomCodes were retrieved
代碼。
刪除此行:
Set rangeMaterialList = MaterialListSheet.Range("B2:B" & Rows.Count)
在應用任何過濾之前 ,插入:
Dim N As Long
N = Cells(Rows.Count, "B").End(xlUp).Row
Set rangeMaterialList = MaterialListSheet.Range("B2:B" & N)
編輯#1 :
您發布的編碼在B列中走得太遠。沒有任何限制它被過濾的表格。 沒有限制,SpecialCells將一直到UsedRange的底部。
我建議的更改將范圍限制在B列中的數據底部。
我在應用過濾器之前指定它的原因是End(xlup)可能不適用於過濾數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.