Excel-VBA循环如果



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

  • 如果第I列中的值 = 1(它要么为空白,要么 = 1(,请查看第G
  • 如果列中的值G<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

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

子宏1 (( 将 rngCell 调暗为范围,_ rng数据范围作为范围

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

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

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

最新更新