我想遍历一行以查看一个单元格的值是否大于或小于下一个单元格的值。如果它更大,则将值输入为1。如果它较小,则将值输入为0。新的0和1值正在创建一个新表,这就是我需要第二个For语句用于遍历新表的原因并输入正确的值。
我已经尝试过嵌套循环,但是它不起作用。
For Each cel In Range("C748:BQ758")
If cel.Value < cel.Next.Value Then
For Each cel In Range("C904:BQ904")
cel.Value = ClosedOutput
ElseIf cel.Value > cel.Next.Value Then
For Each cel In Range("C904:BQ904")
cel.Value = OpenOutput
End If
Next cel
答案 0 :(得分:0)
正如Mathieu Guindon在评论中提到的那样,您缺少代码中的Next语句。您还两次使用cel(如果我没有记错的话)会弄乱事情,因此您需要运行两个不同的变量。这就是它的外观。
For Each Mcel In Range("C748:BQ758")
If Mcel.Value < Mcel.Next.Value Then
For Each Scel In Range("C904:BQ904")
Scel.Value = ClosedOutput
Next
ElseIf Mcel.Value > cel.Next.Value Then
For Each Scel In Range("C904:BQ904")
Scel.Value = OpenOutput
Next
End If
Next cel
但是,您可以通过以下方法将For循环数减少一个:
For Each Mcel In Range("C748:BQ758")
For Each Scel In Range("C904:BQ904")
If Mcel.Value < cel.Next.Value Then
Scel.Value = ClosedOutput
Else
'this allows for an equals to situation (you can change < to <= if you want it equal to the ClosedOutput value.
Scel.Value = OpenOutput
End If
Next
Next
答案 1 :(得分:0)
根据我的评论,使用Variant数组加快速度:
Sub load()
With Worksheets("Sheet1") ' Change to your sheet
Dim ClosedOutput As Integer
ClosedOutput = 0
Dim OpenOutput As Integer
OpenOutput = 1
Dim inArr As Variant
inArr = .Range("C748:BQ758")
Dim outArr() As Variant
ReDim outArr(1 To UBound(inArr, 1), 1 To UBound(inArr, 2))
Dim i As Long
For i = 1 To UBound(inArr, 1)
Dim j As Long
For j = 1 To UBound(inArr, 2) - 1
If inArr(i, j) < inArr(i, j + 1) Then
outArr(i, j) = ClosedOutput
Else
outArr(i, j) = OpenOutput
End If
Next j
Next i
.Range("C904").Resize(UBound(outArr, 1), UBound(outArr, 1)).Value = outArr
End With
End Sub