2017-09-06 85 views
0

我的代码的目的是打印仅当存在betweeen L1任何数据长度7.错误在VBA代码

的W1000虽然它发现长度为7的值,我的代码不服从出口对于。

是什么原因?

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 
+0

哪里定义了k? –

+0

k被定义在顶部 我只包括我有问题的部分。 –

回答

1

如果找到available值,则需要退出嵌套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 
+0

我的循环仍然没有退出! –

+0

@AnirudhChauhan - 用'F8'开始逐步调试,并注意'arrElem'是什么以及它的价值。例如在'If Len(arrElem)= 7'之前添加'debug.print arrElem'。希望在按下'F8'约30分钟后,你会看到解决方案。 – Vityata