用行/列变量编写While循环?

时间:2018-11-21 15:44:17

标签: vba while-loop

我对VBA还是很陌生,仍在尝试学习所有内容。我编写了此简单代码,以提示输入缺少单元格。我想将此应用于其他单元格,即日期,班次等,但我不确定如何编写while循环。所有单元格都在第2行中。

Private Sub Workbook_BeforeClose(Cancel As Boolean)
If Cells(2, 5).Value = "" Then
    MsgBox "Operator Name Required", vbInformation, "ALERT: Missing Information"
    Cancel = True
End If
End Sub

2 个答案:

答案 0 :(得分:0)

欢迎使用StackOverflow。

当然可以使用While loop,但是最好的方法是使用For loop

假设您的单元格位于第2行的第5、6、7和8列。 因此,您要做的是:

For i = 5 To 8
    If Cells(2, i).Value = "" Then
        MsgBox "Operator Name Required", vbInformation, "ALERT: Missing Information"
        Cancel = True
    End If
Next

让我解释一下这是怎么回事:

我们创建了一个变量i,每次内部代码重复执行时,该变量的值都从5更改为8。 因此,我们使用该变量i设置我们的列索引值,在每个所需的列之间进行插入。

当然,提示将始终显示“ Operator Name Required”,而这可能并不是您所需要的。

在这种情况下,您必须创建多个If-End If语句,捕获每个所需的单元格,例如:

If Cells(2, 5).Value = "" Then
    MsgBox "Operator Name Required", vbInformation, "ALERT: Missing Information"
    Cancel = True
End If

If Cells(2, 6).Value = "" Then
    MsgBox "Operator Id Required", vbInformation, "ALERT: Missing Information"
    Cancel = True
End If

If Cells(2, 7).Value = "" Then
    MsgBox "Operator Date of Birth Required", vbInformation, "ALERT: Missing Information"
    Cancel = True
End If

答案 1 :(得分:0)

我不是while循环的忠实拥护者,我想确切地知道循环将运行多长时间,所以我的建议是稍微不同的循环。

Private Sub Workbook_BeforeClose(Cancel As Boolean)

    Dim firstCol As Long, lastCol As Long
    firstCol = 5
    lastCol = 10

    Dim C As Long   'Your variable to loop through columns

    Dim sht As Worksheet
    Set sht = ActiveWorkbook.Sheets("Your Sheet Name To Check")   'Without declaring and using this, if the user is _
                                                                    on a different sheet than the one intended for this macro, _
                                                                    the macro will fire up even if the user already completed

    For C = firstCol To lastCol
        If sht.Cells(2, C).Value = "" Then
            MsgBox "Operator " & sht.Cells(1, C).Value & " Required", vbInformation, "ALERT: Missing Information"
            Cancel = True
        End If
    Next C

End Sub

如果您认为将来列数会改变,则可以更动态地分配 lastCol 变量,有关获取最后一行/列的进一步帮助,请参见此:https://www.thespreadsheetguru.com/blog/2014/7/7/5-different-ways-to-find-the-last-row-or-last-column-using-vba

PS:@Lodi已经回答了类似的问题,但是在撰写本文时,无论如何这是我的2美分。