简体   繁体   English

VBA循环,直到单元格不为空

[英]VBA Loop until cell not blank

I'm sure this is going to be fairly straight forward but I am struggling with this logic. 我敢肯定这将是相当简单的,但是我正在为这种逻辑而苦苦挣扎。 I'm trying to create a row count based on populated data and then loop through all the empty cells in until it fields that the notes column in populated. 我正在尝试根据填充的数据创建行数,然后循环遍历所有空单元格,直到它填充了notes列中的字段。 The idea is that this value/note is then written to a SQL table. 想法是将该值/注释随后写入SQL表。

The code I have so far is: 到目前为止,我的代码是:

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

I know this code is not working as my For Loop is not aligned but I'm just trying to show what I am trying to achieve. 我知道这段代码无法正常工作,因为我的For循环未对齐,但是我只是想展示自己想要实现的目标。

This can be achieved with a little shorter and simplier, using the code below: 使用以下代码,可以更短,更简单地实现这一目标:

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

You might find some methods are quite slow if you have a lot of data. 如果您有大量数据,您可能会发现某些方法非常慢。 This will be quicker than looping through every cell in the column: 这比遍历列中的每个单元更快:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM