在VBA代码中出错

我的代码的目的是在长度为7的L1到W1000之间有任何数据时打印。

虽然它发现长度为7的值,但是我的代码不服从exit。

是什么原因?

Private Sub CommandButton1_Click() Dim Prod As Variant Dim Dev As Variant Dim counter As Integer Dim j As Variant Prod = Array("PBA_100", "PCA_500", "PRD_500", "PGA_500", "PVD_500") For j = LBound(Prod) To UBound(Prod) MsgBox Prod(j) With ThisWorkbook.Sheets(Prod(j)) LastRow = ThisWorkbook.Sheets(Prod(j)).Columns("A").Cells.Find("*", SearchOrder:=xlByRows, LookIn:=xlValues, SearchDirection:=xlPrevious).Row For Each cell In .Range("N2:N" & LastRow) arr = Split(Replace(cell.Value, " ", " "), " ") For Each arrElem In arr If Len(arrElem) = 7 Then MsgBox arrElem Exit For Else MsgBox arrElem End If Next arrElem Next cell End With Next j End Sub 

如果findavailable值,则需要退出嵌套for循环。 喜欢这个:

 With ThisWorkbook.Sheets(Prod(j)) LastRow = ThisWorkbook.Sheets(Prod(j)).Columns("A").Cells.Find("*", SearchOrder:=xlByRows, LookIn:=xlValues, SearchDirection:=xlPrevious).Row For Each cell In .Range("L1:W1000", .Cells(.Rows.Count, "A").End(xlUp)) arr = Split(Replace(cell.Value, " ", " "), " ") For Each arrElem In arr If Len(arrElem) = 7 Then ThisWorkbook.Sheets("Sheet1").Range("D" & k).Value = "available" Exit For 'You exit only the nested loop here! Else ThisWorkbook.Sheets("Sheet1").Range("D" & k).Value = "NOT available" End If Next arrElem Next cell End With