2017-09-06 66 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