VBA While循环不会迭代

时间:2020-07-29 13:42:36

标签: excel vba

我有一个项目,必须在同一行上检查“ I”是否为空,“ k”也必须为空。 如果没有的话,我将背景涂成红色。

我执行该代码。不会崩溃,但也没有效果……

Sub JK()

Dim count As Integer
Dim emptyJ As Boolean
Dim emptyK As Boolean

    count = 1
    
While count = 999

    emptyJ = isEmpty(Cells(count, J).Value)
    emptyK = isEmpty(Cells(count, K).Value)

    If emptyJ = True Then
        If emptyK = False Then
            Range(Cells(J, count), Cells(K, count)).Select
            With Selection.Interior
            .Pattern = xlSolid
            .PatternColorIndex = xlAutomatic
            .Color = 255
            .TintAndShade = 0
            .PatternTintAndShade = 0
            End With
        Else
        End If
    Else
    End If
    
    count = count + 1
    
 Wend

End Sub

2 个答案:

答案 0 :(得分:1)

如上所述,我将通过条件格式解决问题。但是,如果您想使用VBA进行此操作,则以下代码可以提供帮助

Sub JK()
    For i = 1 To ActiveSheet.UsedRange.Rows.Count
    
        If IsEmpty(Cells(i, 10)) And Not IsEmpty(Cells(i, 11)) Then
            Range(Cells(i, 10), Cells(i, 11)).Interior.Color = 255
        Else
            Range(Cells(i, 10), Cells(i, 11)).Interior.Pattern = xlNone
        End If
    Next i
End Sub

答案 1 :(得分:0)

向您提出建议。他们现在工作完美。 我的错误出现在“ K”单元格上,该单元格包含2个命题-“”和-“ texte”。 在dat情况下,我们不能说“ K isEmpty”。但是带有dat代码

Sub JK()

Dim count As Long

' Change the sheet name
With ThisWorkbook.Sheets("Sheet 1")
    count = 1
    While count <= 999
        With .Cells(count, "J")
            If .Value = "" Then
                If Not (.Offset(0, 1).Value) = "" Then
                    With .Resize(1, 2).Interior
                        .Pattern = xlSolid
                        .PatternColorIndex = xlAutomatic
                        .Color = 255
                    End With
                End If
            End If
        End With
        
        count = count + 1
    Wend
End With

结束子

有效

或者那个:

Sub JK()

对于i = 1到ActiveSheet.UsedRange.Rows.count

    If (Cells(i, 10).Value) = "" And Not (Cells(i, 11).Value) = "" Then
        Range(Cells(i, 10), Cells(i, 11)).Interior.Color = 255
    Else
    End If
Next i

结束子

相关问题