Excel-VBA循环ifs

时间:2017-08-10 14:42:24

标签: excel vba excel-vba

我已经编写了2个宏来完成这项任务,但我正在努力巩固并提高效率。

  • 如果列I中的值= 1(它将为空或= 1),请查看列G
  • 如果列G中的值&lt; 30如果H列中的值< 0.03那么 将第I列中的值覆盖为=“0”...(如果不是,则不要更改列I中的值,然后继续检查下一个)

范围为I9:I45000G9:G45000H9:H45000

我认为有一个简单的解决方案,但几个小时后,我没有受过教育的自己找不到它。

模块1:

Dim rngCell As Range, _
    rngDataRange As Range

Set rngDataRange = Range("G9:G45000")
For Each rngCell In rngDataRange
    With rngCell
        If .Value < 30 Then
            .Offset(0, 2).Value = "0"    'A[rngCell] to C[rngCell]
        End If
    End With
Next rngCell
End Sub

单词数:

Sub Macro1()
Dim rngCell As Range, _
    rngDataRange As Range

Set rngDataRange = Range("H9:H45000")

For Each rngCell In rngDataRange
    With rngCell
        If .Value < 0.03 Then
            .Offset(0, 1).Value = "0"    'A[rngCell] to C[rngCell]
        End If
    End With
Next rngCell
End Sub

这是我首先运行的宏....它将值放在第一列的某些单元格中(其中列C的值小于1575):

Sub Macro1()     Dim rngCell作为范围,_     rngDataRange作为范围

Set rngdataRange = Range (C9:C45000)

For Each rngCell In rngDataRange
    With rngCell
        If .Value < 1575 Then
           .Offset (0,6).Value="1"
        End If
    End With
Next rngCell

End Sub

4 个答案:

答案 0 :(得分:2)

这应该可以胜任。

Sub CheckClmI()

    Dim Rl As Long                      ' Last row
    Dim R As Long

    Application.ScreenUpdating = False
    With ActiveSheet
        ' Used range should be enough
        Rl = .UsedRange.Rows.Count

        For R = 9 To Rl
            If Val(.Cells(R, "I").Value) = 1 Then
                If Val(.Cells(R, "G").Value) < 30 Or _
                   Val(.Cells(R, "H").Value < 0.03) Then
                   .Cells(R, "I").Value = 0
                End If
            End If
        Next R
    End With
    Application.ScreenUpdating = True
End Sub

答案 1 :(得分:0)

这样的事情怎么样?

Sub Macro1()
    OnError Goto OopsIDidItAgain
    Dim rngCell As Range, rngDataRange As Range

    Application.ScreenUpdating = False
    Set rngDataRange = Range("G9:G45000")

    For Each rngCell In rngDataRange
        With rngCell
            If .Value < 30 Or .Offset(0, 1).Value < 0.03 Then .Offset(0, 2).Value = "0"
        End With
    Next rngCell
OopsIDidItAgain:
    Application.ScreenUpdating = True
End Sub

答案 2 :(得分:0)

您可以一次性完成所有测试:

Dim rngCell As Range
Dim rngDataRange As Range
Dim iCell as range
Dim hVal as variant

Set rngDataRange = Range("G9:G45000")
For Each rngCell In rngDataRange
    With rngCell
        Set iCell = .Offset (0,2)
        hVal = .Offset (0,1).Value

        If iVal = 0 or iVal = vbnullstring then
            If .Value < 30 or hVal > .3 Then
                iCell.Value = "0"    
            End If
        End if
    End With
 Next rngCell
 End Sub

答案 3 :(得分:0)

我喜欢计算行数,因此您不会浪费循环。

Dim LstRw As Long
Dim Rng As Range, c As Range

LstRw = Cells(Rows.Count, "G").End(xlUp).Row
Set Rng = Range("G9:G" & LstRw)
For Each c In Rng.Cells
    If c < 30 Or c.Offset(, 1) < 0.03 Then c.Offset(, 2) = 0
Next c