如何停止一个For …下一个在Excel中的button?

下面的代码是我从网上find的解决scheme修改的。 表单的上下文。

该表单有一个带有3个button的combobox(Add,Next,Done)

  • 添加将粘贴任何从combobox中select
  • 接下来应该移动到列中的下一个空单元格(下面的代码)
  • 完成后应closures表单,以便查看电子表格(代码如下)

我碰到的是,当我点击“完成”button,它不会closures,如果我已经运行“下一步”。 For … Next循环直到所有空格都被填充。 我想要的是一种方法来停止for循环,当我点击“完成”我已经尝试添加一个语句,以显示当前单元格有字符退出,但它只是杀死了代码,它不会运行。 所以我现在亏本了,如果有人能帮上忙的话那就太好了。 谢谢。

Private Sub nxtBtn_Click() Dim sourceCol As Integer, rowCount As Integer, currentRow As Integer Dim currentRowValue As String, cString As String sourceCol = 7 'column G has a value of 7 rowCount = Cells(Rows.count, sourceCol).End(xlUp).Row 'for every row, find the first blank cell and select it For currentRow = 4 To rowCount currentRowValue = Cells(currentRow, sourceCol).Value If IsEmpty(currentRowValue) Or currentRowValue = "" Then Cells(currentRow, sourceCol).Select End If Next End Sub Private Sub done_bn_Click() 'Refresh the workbook/pivot tables ThisWorkbook.RefreshAll 'Close form Unload Me End Sub 

而不是使用循环find列F中的第一个空白单元格,只需使用Range.Find方法即可。 你可以用这一行replace你的整个循环:

 Columns("F").Find(vbNullString, Range("F3"), xlValues, xlWhole).Select 

这样,你不必退出代码执行,因为这将find单元格F3(我猜是一个头)后列F中的第一个空白单元格,没有循环需要。

您将需要暂停循环,并检查发送到该程序的任何事件。

在VBA中,有DoEventsfunction。 用通俗的话来说,这个程序可以让程序“追上自己”。 所以,我build议添加一个DoEvents到你的循环,然后检查击键。 您想要捕获Ctrl / Break键,这将暂停VBA。

我在想这样的事情:

 Private Sub nxtBtn_Click() Dim sourceCol As Integer, rowCount As Integer, currentRow As Integer Dim currentRowValue As String, cString As String sourceCol = 7 'column F has a value of 7 rowCount = Cells(Rows.count, sourceCol).End(xlUp).Row 'for every row, find the first blank cell and select it For currentRow = 4 To rowCount currentRowValue = Cells(currentRow, sourceCol).Value If IsEmpty(currentRowValue) Or currentRowValue = "" Then Cells(currentRow, sourceCol).Select End If 'Allow the code to catch up, so it can determine if Ctrl/Break were sent DoEvents Next End Sub Private Sub done_bn_Click() 'Send the Ctrl/Break keys to Excel Application.SendKeys("^{BREAK}") 'Refresh the workbook/pivot tables ThisWorkbook.RefreshAll 'Close form Unload Me End Sub