繁体   English   中英

对于每个循环范围VBA Excel宏

[英]For Each Loop Ranges VBA Excel Macro

If Range("D32").Value = 2 Then
   If Range("D15").Value = 0 Then
      Range("D15").Value = 1
      Range("D32").Value = 1
   End If
End If

我一直在尝试找出如何将这些值放入每个循环的a中。

基本上,如果D15-> AE15 = 2且D32-> AE32 = 0,则将两个值都更改为1。

我考虑过对每个单元重复上述嵌套的IF语句..但这会花费一些时间。

For Each c In Worksheets("sheet1").Range("D32:AE32").Value

If Range("D32") = 2 Then


Range("D15").Value = 1
Range("D32").Value = 1

End If
Next c

这适用于一个单元。 但是我很困惑如何获取它来检查整个行,然后在1为2时更改15和32的相应列值。

试试看,您走在正确的轨道上:

Sub ChgValues()
    Dim c As Range, d As Range

    For Each c In Range("D15:AE15")
        Set d = c.Offset(17, 0)
        If c.Value = 0 And d.Value = 2 Then
            c.Value = 1
            d.Value = 1
        End If
    Next c
End Sub

编辑:
上面的代码将检查从D到AE的所有列的第15行的0和第32行的2。 如果值也可以相反(第15行中为2,第32行中为0),则需要进行其他比较:

更改

If c.Value = 0 And d.Value = 2 Then

If (c.Value = 0 And d.Value = 2) or (c.Value = 2 And d.Value = 0) Then

您需要为每个循环提供一个集合,然后检查值。

Dim cell As Range
For Each cell In Range("D15:AE15").Cells
    If cell.Value = 0 And cell.Offset(17).Value = 2 Then
        cell.Value = 1
        cell.Offset(17).Value = 1
    End If
Next cell

暂无
暂无

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

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