Excel-VBA循环ifs

我已经写了2个macros来完成这个任务,但我正在尝试整合,并使其更有效率。

  • 如果列I的值为1(它将为空或= 1),请查看G
  • 如果列G的值<30或列H的值<0.03,则将列I中的值重写为=“0”…(如果不是,则不要更改列I的值并继续检查下一个)

范围是I9:I45000G9:G45000H9:H45000

我认为有一个简单的解决scheme,但几个小时后,我的未受教育的自我找不到。

模块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 

这是我第一次运行的macros….它将列中的一些单元格中的值(其中列C的值小于1575):

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

 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 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 

你可以一口气做所有的testing:

 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