我正在尝试循环工作表中的所有非隐藏和非空白行。问题是,它确实循环通过非隐藏,但当它到达非隐藏工作表的末尾时,它就会一直持续下去。
我知道它在过滤器之后检索了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
代码。
答案 0 :(得分:2)
删除此行:
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)可能无法处理过滤后的数据。