在Excel中如何判断VBA循环,达到条件时中止循环

2025-03-03 19:41:12
推荐回答(2个)
回答1:

  1. 启动excel后按Alt+F11启动VBA编辑环境,并在左侧点击右键→插入→用户窗体。在工具栏中,添加按钮到窗体:


  2. 双击按钮,并添加如下代码

    Private Sub CommandButton1_Click()
        Dim lastRow, i As Long
        With Sheets(1)
            lastRow = Sheets(1).UsedRange.Rows.Count
            For i = 1 To lastRow
                If TextBox1.Text = .Range("A" & i).Value Then
                     .Range("A" & i).Select
                     Exit For
                End If
            Next
        End With
    End Sub


  3. 在VBA中运行窗口,测试结果为输入10,A列单元格的10被选中:

回答2:

Private Sub CommandButton1_Click()
Dim intTemp As Long
Dim I As Long
intTemp = Int(TextBox1.Text)
For I = 1 To 65534
If Sheet3.Cells(I, 1) = intTemp Then
Sheet3.Cells(I, 1).Select
Exit For
End If
Next
End Sub

sheet3要换成你的数据所在表