VBA在迭代期间控制用户焦点

时间:2011-08-01 15:39:34

标签: vba excel-vba excel

快速问题,不应该真正需要我的任何代码。在我的应用程序中,我使用'for each'循环,循环遍历一系列单元格,现在当用户运行它时,屏幕的焦点跟随选择,因为它在该范围内从一个单元跳转到单元格。有没有办法阻止焦点在迭代过程中跟随循环的路径,也许让用户只看到“处理”的内容直到它完成?

提前致谢,我感谢任何帮助。

代码:

Dim iLoop As Integer

For iLoop = 5 To lastRow

 Sheets("Planners").Activate
 Range("J" & iLoop).Select
 Range(Cells(iLoop, 9)).Select

 With Selection.Validation
    .Delete
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
    xlBetween, Formula1:="Yellow, Orange, Green, Red"
    .IgnoreBlank = True
    .InCellDropdown = True
    .InputTitle = ""
    .ErrorTitle = ""
    .InputMessage = "Invalid Entry"
    .ErrorMessage = "Please choose from dropdown"
    .ShowInput = True
    .ShowError = True
 End With

Next iLoop

2 个答案:

答案 0 :(得分:1)

显然您在代码中使用.Select。有可能做到这一点是正确的,但大部分时间都没有。

请停止使用SelectActiveCell并使用索引/引用引用单元格。

以上是正确的解决方案 错误的解决方案是在循环之前使用Application.ScreenUpdating = False并在循环之后使用Application.ScreenUpdating = True


编辑:

Dim iLoop As long
dim w as worksheet

set w = Worksheets("Planners")

For iLoop = 5 To lastRow

  With w.cells(iLoop, 9).Validation
    .Delete
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
    xlBetween, Formula1:="Yellow, Orange, Green, Red"
    .IgnoreBlank = True
    .InCellDropdown = True
    .InputTitle = ""
    .ErrorTitle = ""
    .InputMessage = "Invalid Entry"
    .ErrorMessage = "Please choose from dropdown"
    .ShowInput = True
    .ShowError = True
  End With

Next

但鉴于此代码,您根本不需要循环:

dim w as worksheet
set w = Worksheets("Planners")

With w.Range(w.cells(5, 9), w.cells(lastRow, 9)).Validation
  .Delete
  .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
  xlBetween, Formula1:="Yellow, Orange, Green, Red"
  .IgnoreBlank = True
  .InCellDropdown = True
  .InputTitle = ""
  .ErrorTitle = ""
  .InputMessage = "Invalid Entry"
  .ErrorMessage = "Please choose from dropdown"
  .ShowInput = True
  .ShowError = True
End With

答案 1 :(得分:0)

您需要做的就是在代码开头添加application.screenupdating = false(在课程的子定义之后),并在'end sub'之前的末尾添加application.screenupdating = true。

最好将它添加到所有子和函数中,因为它会使它们运行得更快。