我在if语句内的循环内分配变量值。当if语句退出时,变量值变为未分配状态。我需要保留变量值,因为在下一次迭代中需要更新后的值。
在下面的示例中,我从Z = 2开始,然后进入循环,循环中的第一个IF语句检查Z = 2,然后执行作业,然后重新分配Z = 1,然后退出该语句,并在下一个执行i循环迭代开始,Z的值不再为1,而是再次为2。如何为下一次i迭代保留值?
Sub qwer()
Z = 2
For i = 2 To 80
If Z = 2 Then
For l = 2 To 80
If Cells(l, "A").Value = 2 Then
Cells(i, "F").Value = Cells(l, "E").Value
Cells(l, "A").Value = ""
Z = Cells(l, "C").Value
Exit For
End If
Next
End If
Exit For
If Z = 1 Then
For l = 2 To 80
If Cells(l, "A").Value = 1 Then
Cells(i, "F").Value = Cells(l, "E").Value
Cells(l, "A") = ""
Z = Cells(l, "A").Value
Exit For
End If
Next
End If
答案 0 :(得分:0)
在Sub qwer()之前写入:
Public z As Long
这将在您运行代码时保留值。 如果您停止执行该代码,则建议您保存到VeryHidden工作表中。
我希望蒂沃能为您服务!
答案 1 :(得分:0)
Sub qwer()
Z = 2
For i = 2 To 800
If Z = 2 Then
For l = 2 To 80
If Cells(l, "A").Value = 2 Then
Cells(i, "F").Value = Cells(l, "E").Value
Cells(l, "A").Value = ""
Z = Cells(l, "C").Value
Exit For
End If
Next
ElseIf Z = 1 Then
For l = 2 To 80
If Cells(l, "A").Value = 1 Then
Cells(i, "F").Value = Cells(l, "E").Value
Cells(l, "A") = ""
Z = Cells(l, "C").Value
Exit For
End If
Next
ElseIf Z = 3 Then
For l = 2 To 80
If Cells(l, "A").Value = 3 Then
Cells(i, "F").Value = Cells(l, "E").Value
Cells(l, "A") = ""
Z = Cells(l, "C").Value
Exit For
End If
Next
ElseIf Z = 4 Then
For l = 2 To 80
If Cells(l, "A").Value = 4 Then
Cells(i, "F").Value = Cells(l, "E").Value
Cells(l, "A") = ""
Z = Cells(l, "C").Value
Exit For
End If
Next
ElseIf Z = 5 Then
For l = 2 To 80
If Cells(l, "A").Value = 5 Then
Cells(i, "F").Value = Cells(l, "E").Value
Cells(l, "A") = ""
Z = Cells(l, "C").Value
Exit For
End If
Next
End If
Next i
End Sub