对于每个循环范围VBA Excelmacros

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

我一直在试图找出如何把这些值在每个循环内。

基本上如果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 

这适用于一个单元格。 然而,我很难看到如何让它检查整个行,然后更改相应的列值为15和32时,一个是2。

试试这个,你在正确的轨道上:

 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