增量嵌套循环if语句vba

时间:2019-05-04 15:54:08

标签: excel vba loops

我有一段代码可以执行嵌套的If语句。易于嵌套在Excel中,但难于在VBA中。

我想将嵌套的If自动化为代码,该代码可以递增到最后一行,并且每次通过都会更改范围。
我已经看过这里的答案,但是很困惑。

Excel If=IF(C2 > 1.42, A2, IF(D2 > 1.42, B2, "FAIL"))

到目前为止,我的VBA尝试是:

Sub ResultData()
    If Range("C2").Value > 1.42 Then
       Range("E2") = Range("A2")

    ElseIf Range("D2").Value > 1.42 Then
        Range("E2") = Range("B2")

    Else: Range("E2") = "FAIL"

    End If
End Sub

只希望代码向下排到最后一行,在本例中为第53行。

Current data

2 个答案:

答案 0 :(得分:1)

类似的事情应该对您有用:

Sub ResultData()
  For i = 2 to 53
    If Cells(i, 3).Value > 1.42 Then
      Cells(i, 5).Value = Cells(i, 1).Value
    ElseIf Range("D2").Value > 1.42 Then
      Cells(i, 5).Value = Cells(i, 2).Value
    Else
      Cells(i, 5).Value = "FAIL"
    End If
  Next
End Sub

答案 1 :(得分:-1)

既然您的问题已经得到回答,我想我应该重点介绍您应该采用的良好做法。

此外,由于已经显示了cells方法,所以我认为也可以显示如何使用范围代替。

注释应指导您完成基本逻辑。

Option Explicit 'Always add this line. It prevents you from using a variable without having declared it.
Sub ResultData()
Dim wb As Workbook 'declare a workbook variable which can hold a workbook object
Dim sht As Worksheet 'declare a worksheet variable which can hold a worksheet object
Dim i As Long 'declare a variable that will hold the row index. This should always be of type Long
Set wb = ThisWorkbook 'assign the workbook where your code is, to your workbook variable.
Set sht = wb.Worksheets("The name of your Worksheet") 'assign the worksheet where your data is, to your worksheet variable.

For i = 2 To 53 Step 1 'loop through rows 2 to 53
                                                    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    If sht.Range("C" & i).Value > 1.42 Then         'Refer to ranges and cells by using explicit references to the                  '
        sht.Range("E" & i) = sht.Range("A" & i)     'worksheets to which they belong. So, sht.range("A1") refers to cell A1 of sht. '
    ElseIf sht.Range("D" & i).Value > 1.42 Then     'You can dynamically refer to a range by concatenating the column's index letter'
        sht.Range("E" & i) = sht.Range("B" & i)     'with a dynamically changing variable which represents the row's index.         '
    Else                                            'So sht.Range("D" & "3") for example refrs to sht.Range("D3").                  '
        sht.Range("E" & i) = "FAIL"                 '                                                                               '
    End If                                          '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Next i

End Sub