在Excel VBA中执行循环时如何选择空白和单元格?

时间:2018-07-28 09:09:05

标签: excel vba

我想在F列粘贴“ Thomos”六次,其中F列的单元格值为空白,J列的单元格值为非空白。

此后,我想在F列中粘贴“杰瑞”六次,其中K列中的单元格值为非空白,F列中的单元格值为空白。

运行代码时,将jerry粘贴到存在Thomos的F列的单元格中。

Sub populate()

Dim iVal As Integer
Dim Val As Integer
For Each Cel In Range("J2:J100")
    For Each blk In Range("F2:F100")
        If Cel.value <> "" And blk.value = "" Then
            Cel.Offset(0, -4).value = "Thomos"
        Else
        End If
        iVal = Application.WorksheetFunction.CountIf(Range("F2:F100"), "Thomos")
        If iVal = 6 Then
            Exit For
        End If
    Next
Next

For Each Rng In Range("K2:K100")
    For Each blk2 In Range("F2:F100")
        If Rng.value <> "" And blk2.value = "" Then
            Rng.Offset(0, -5).value = "jerry"
        Else
        End If
        Val = Application.WorksheetFunction.CountIf(Range("F2:F100"), "jerry")
        If Val = 6 Then
            Exit For
        End If
    Next
Next
End Sub

2 个答案:

答案 0 :(得分:0)

每次浏览FJ中的一个单元格时,您将循环访问K中的所有单元格。因此,如果(例如)对于单元格Cel的{​​{1}}不是""并且对于单元格K4的{​​{1}}是blk2,则您已满足条件不管 it 是否为空白,都会为""F9赋值。您只需一个即可:

K4.Offset(0,-5)

替代方法:

Jerry

答案 1 :(得分:0)

非常感谢您的帮助。以下是我在您的帮助下编写的代码。

Sub populate()

Dim iVal As Integer
Dim iVal2 As Integer
iVal = Application.WorksheetFunction.CountIf(Range("F2:F100"), Range("x2"))
iVal2 = Application.WorksheetFunction.CountIf(Range("F2:F100"), Range("x3"))
ival3 = Application.WorksheetFunction.CountIf(Range("F2:F100"), Range("x4"))
iVal1 = 0
iVal2 = 0
ival3 = 0
For Each Cel In Range("F2:F100")
    If Cel.value = "" And Cel.Offset(0, 4).value <> "" And iVal < Range("y2") Then
        Cel.value = Range("x2")
        iVal = iVal + 1
    End If
    If Cel.value = "" And Cel.Offset(0, 5).value <> "" And iVal2 < Range("y3") Then
        Cel.value = Range("x3")
        iVal2 = iVal2 + 1
    End If
        If Cel.value = "" And Cel.Offset(0, 6).value <> "" And ival3 < Range("y4") Then
        Cel.value = Range("x4")
        ival3 = ival3 + 1
    End If
    If iVal1 = Range("y2") And iVal2 = Range("y3") And ival3 = Range("y4") Then
        Exit For
    End If
Next
End Sub