For循环内的if语句

时间:2019-01-15 18:52:00

标签: arrays excel vba for-loop if-statement

我正在尝试让for循环通过一列以查找“否”,如果未找到“否”,它将在另一个单元格中输出“是”。因此,我的思维过程是进行for循环,然后执行if语句,如果该单元格显示“是”或“没有要求”,则它将继续寻找“否”,如果未找到“否”,则输出“是”,如果找到,则循环停止,并输出“否”。

我正在制作一个工具,可以从同一Excel工作簿上的不同工作表中提取数据。

Sub PleaseWork()

Dim matrix(i, j) As Double


For i = 26 To 33
    For j = 8 To 8
        If Worksheets("Calculations").Range(i, j) = "Yes" Or "No Requirement" Then
            Worksheets("Calculations").Range("H33").Value = "Yes"
            Next i
        Else
            Worksheets("Calculations").Range("H33").Value = "No"
        End If



End Sub

该代码甚至无法运行,每次尝试运行它时都会出现编译错误。我是VBA的新手,并且知道这可能超级简单,但我似乎无法理解。

3 个答案:

答案 0 :(得分:1)

Next i必须位于If-End If之外,并且需要在Next j循环中添加For i才能使代码运行。此外,如果j = 8的第二个循环只会运行一次,则可以完全消除它。

说起来容易得多

For i = 26 To 33
    If Worksheets("Calculations").Cells(i, 8) = "Yes" Or Worksheets("Calculations").Cells(i, 8) = "No Requirement" Then
        Worksheets("Calculations").Range("H33").Value = "Yes"
    Else
        Worksheets("Calculations").Range("H33").Value = "No"
    End If
Next i

答案 1 :(得分:0)

我不确定如果只浏览一列,为什么在这里使用矩阵。

下面的代码将检查该列(如果您愿意的话,可以将其设为动态范围),并在第一个值“ No Requirement”的单元格处停止-然后输出该值的单元格地址和“否”并退出循环。

Sub RandomCol()

For Each cell In Worksheets("Calculations").Range("A1:A50")

    If cell.Value = "Yes" Or cell.Value = "No Requirement" Then

    ElseIf cell.Value = "No" Then
        Range("H33").Value = (cell.Address + " " + "No")
        Exit For
    End If

Next cell

End Sub

答案 2 :(得分:0)

我希望这会有所帮助。

以下应该适合您的目的:

    Sub RunIt()
      '          A, E, 1, 5
      PleaseWork 1, 5, 1, 5
    End Sub

    Sub PleaseWork(intFromCol As Integer, intToCol As Integer, intFromRow As Integer, _
                   intToRow As Integer)

        Dim intI As Integer
        Dim intJ As Integer
        Dim blnFoundNo As Boolean
        Dim strOut As String

        strOut = "Yes"
        blnFoundNo = False
        For intI = intFromCol To intToCol
            For intJ = intFromRow To intToRow
                '                                     Row , Col
                With Worksheets("Calculations").Cells(intJ, intI)
                    If LCase(Trim(.Value)) = "no" Then
                        strOut = Replace(Cstr(.Address), "$", "") & " = No"
                        blnFoundNo = True
                        Exit For
                    End If
                End With
            Next intJ
            If blnFoundNo Then Exit For
        Next intI

        Worksheets("Calculations").Range("H33").Value = strOut

    End Sub