首页 > 解决方案 > 将变量值保持在循环之外

问题描述

我在 if 语句内的循环中分配变量值。当 if 语句退出时,变量值变为未赋值。我需要保留变量值,因为我需要在下一次迭代中更新值。

在下面的示例中,我从 Z=2 开始,然后进入循环,循环中的第一个 IF 语句检查 Z=2 然后执行工作然后重新分配 Z=1 然后退出语句,当下一个 i-loop迭代开始,Z 的值不再是 1,而是再次变为 2。如何保持下一次迭代的值?

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

标签: excellifetime

解决方案


before Sub qwer() write:

Public z As Long

That will keep the value while you running your code. If you stop the code im recommend to save into a VeryHidden sheet.

I hope thiw works for you!


推荐阅读