繁体   English   中英

Excel-VBA循环ifs

[英]Excel-VBA loop ifs

我已经编写了2个宏来执行此任务,但我正在尝试合并并使其更高效。

  • 如果I列中的值= 1(它将为空白或= 1),则查看G
  • 如果G列中的值<30或H列中的值<0.03 THEN则将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

模组2:

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

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

子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

结束子

这应该做的工作。

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

那这样的东西呢?

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

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

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

我喜欢对行进行计数,以免浪费循环。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM