下一步按钮用户窗体Excel VBA

时间:2018-06-23 18:12:43

标签: excel vba excel-vba

我有一个管理表,其中包含一列包含True和False列表的列。我正在构建一个用户窗体UI,以便用户可以单击“下一步”(现在-在进行下一个工作后构建上一个按钮),该用户窗体将在管理表中显示下一个“ False”项,并且在Sheet1中其对应的数据将显示在Textbox1中。

原因是管理工作表中与Sheet1相关的行ID。因此,如果Sheet1第31行中的数据有问题,则管理表第31行中的第13列将为False。

代码:

Dim n As Long
Private Sub CommandButton1_Click()
Dim LR As Long
LR = Sheets("Sheet1").Cells(Rows.count, "B").End(xlUp).row

n = 7
With Worksheets("Admin")
    For i = n To LR
        If .Cells(i, 13).Value = "False" Then
            With Worksheets("Sheet1")
                Me.TextBox1 = .Cells(i, 2).Value
                Exit For
            End With
        End If
    Next i
End With
n = i + 1

End Sub

此操作成功转到下一个False项目,并在Textbox1中正确显示。但是,它不会迭代到下一个。

无论我们用来设置Next的逻辑是什么,我都将假定Previous是相同的吗?

谢谢大家。

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

Sub cmdNext_Click()
    FindRow True
End Sub

Sub cmdPrev_Click()
    FindRow False
End Sub


Private Sub FindRow(bForward As Boolean)
    Const RW_START As Long = 7

    Dim LR As Long, t As Long, dir As Long, i As Long
    LR = Sheets("Sheet1").Cells(Rows.Count, "B").End(xlUp).Row

    'going forwards, or back?
    If bForward Then
        n = IIf(n = 0, RW_START, n + 1) '<< Start at top
        t = LR                          '<< towards here
        dir = 1                         '<< increasing
    Else
        n = IIf(n = 0, LR, n - 1)       '<< Start at bottom
        t = RW_START                    '<< towards here
        dir = -1                        '<< decreasing
    End If

    For i = n To t Step dir
        If Worksheets("Admin").Cells(i, 13).Value = "False" Then
            Me.TextBox1 = Worksheets("Sheet1").Cells(i, 2).Value
            n = i
            Exit For
        End If
    Next i

End Sub