2017-06-26 40 views
0

我敢肯定,這將是相當簡單的,但我這個邏輯掙扎。我試圖根據填充數據創建行計數,然後循環遍歷所有空單元格,直到它填充填充的註釋列。這個想法是,這個值/註釋被寫入SQL表。VBA循環直到電池不是空白

我到目前爲止的代碼是:

NoteCount = WorksheetFunction.CountA(Sheets("Missing").Range("B10:B7500")) 

Sheets("Missing").Range("L10").Select 

For i = 10 To NoteCount  
    If ActiveCell.Value = "" Then  
     Next i  
    Else:  
     'SQL Code entered here'  
    End If  
Next I 

我知道這個代碼不工作作爲我的For循環未對齊,但我只是想證明什麼,我想要的目的。

+0

你有2'下一個我'必須只有一個。使用倒置的'if'語句代替:'If Not ActiveCell.Value =「」Then'SQL Code Here entered'' –

回答

3

這可以用更短一點,simplier來實現,使用下面的代碼:

Dim i As Long 

With Sheets("Missing") 
    For i = 10 To .Cells(.Rows.Count, "B").End(xlUp).Row ' loop until last row with data in column "B" (skip blank rows) 
     If Trim(.Range("L" & i).Value) <> "" Then ' check if value in cell in column "L" in current row is not empty 
      'SQL Code entered here' 
     End If 
    Next i 
End With 
+0

謝謝Shai,這個工作很完美! – Carlos80

+0

@ Carlos80傻冒歡迎,現在你可以標記爲「答案」通過clickin對我的回答左側灰色複選標記(它會變綠) –

+0

完成 - 再次感謝您! – Carlos80

1

您可能會發現一些方法是相當緩慢的,如果你有大量的數據。這將比循環遍歷列中的每個單元更快:

Sub test() 
    Dim rng As Range, found As Range 
    Dim firstAddress As String 

    With ThisWorkbook.Worksheets("Missing") 
     Set rng = .Range(.Range("B10"), .Cells(.Rows.Count, "B").End(xlUp)) 
     Set rng = rng.Offset(0, 10) 
    End With 

    Set found = rng.Find("", , , xlWhole) 
    If Not found Is Nothing Then 
     firstAddress = found.Address 
     Do 
      'SQL code entered here 
      Set found = rng.FindNext(found) 
     Loop While Not found.Address = firstAddress 
    End If 
End Sub