在多页面中dynamic设置焦点

我做了一个用户表单,所有的字段都是强制的。 这个用户表单上有5个页面。 我需要把重点放在validation空间的领域。 我试图用一个IsError语句

昏暗我作为整数

For Each ctrl In Controls 'loop through Controls and search for Control with the right name i = 0 If ctrl.Value = "" Then MsgBox ctrl.Name, vbExclamation, "Input Data" While IsError(ctrl.SetFocus) UserForm1.MultiPage1.Value = i i = (i + 1) Mod 5 Wend ctrl.SetFocus Exit Sub End If Next 

我也尝试过与一个error handling程序一样没有成功

 Dim i As Integer For Each ctrl In Controls 'loop through Controls and search for Control with the right name i=0 If ctrl.Value = "" Then MsgBox ctrl.Name, vbExclamation, "Input Data" On Error GoTo ErrHandler: ctrl.SetFocus ErrHandler: UserForm1.MultiPage1.Value = i i = (i + 1) Mod 5 Resume Exit Sub End If Next 

任何帮助将不胜感激

看看下面。 这是一种做法。

 Sub example() Dim pageIndx As Integer Dim firstPage As String pageIndx = 0 'leave at 0, first page CurrentPage = "Page1" 'Make sure all pages are named the same, 'with an increasing number at the end(it is like this by default) For Each ctrl In UserForm1.Controls On Error Resume Next Debug.Print ctrl.Name Debug.Print ctrl.Parent.Name If (ctrl.Parent.Name Like "Page*" And ctrl.Parent.Name > CurrentPage) Then pageIndx = pageIndx + 1 End If If ctrl.Value = "" Then UserForm1.MultiPage1.Value = pageIndx: UserForm1.Show MsgBox ctrl.Name, vbExclamation, "Input Data" ctrl.Value = "Input Data" Exit Sub End If Next ctrl End Sub 
  • 然后使用下面的代码在每个文本框_MouseDown子,用户表单代码部分(在这个例子中,它是TextBox3)。 这将清理textBox当用户点击它来键入。

     If (Me.TextBox3.Value = "Input Data") Then Me.TextBox3.Value = "" End If 

这里有一种方法 – 它假定任何Listbox / ComboBox都需要从列表中进行select:

 Private Sub CommandButton1_Click() Dim ctl As MSForms.Control Dim pg As MSForms.Page Dim bFoundOne As Boolean For Each pg In Me.MultiPage1.Pages For Each ctl In pg.Controls Select Case TypeName(ctl) Case "TextBox" If ctl.Value = vbNullString Then bFoundOne = True FlagInvalid pg.Index, ctl Exit For End If Case "ListBox", "ComboBox" If ctl.ListIndex = -1 Then FlagInvalid pg.Index, ctl bFoundOne = True Exit For End If End Select Next ctl If bFoundOne Then Exit For Next pg End Sub Sub FlagInvalid(lngIndex As Long, ctl As MSForms.Control) MsgBox "Please fill out ALL controls" Me.MultiPage1.Value = lngIndex ctl.SetFocus End Sub 

您只能将SetFocus设置为当前所选多页上的已启用控件。 如果在尝试使用SetFocus之前检查MultiPage.Value,则只有当相关的MultiPage页面处于焦点状态时才可以select设置焦点,或者可以将MultiPage.Value更改为控件所在的页面,然后使用SetFocus。 您可能还必须先将SetFocus设置为控件所在的任何框架。

您也可能想要考虑在执行validation的同时获取第一个未通过validation的控件的名称,然后简单地使用

 Controls(<nameofcontrol>).SetFocus 

下面是一些示例代码 – 我为MultiPage值使用公共枚举,而mvarlMeasuresControlSets是度量值控制集的计数器,每当用户需要input新的度量值时,都会dynamic创build它们:

 ' Ensure that fraMeasures has focus and then SetFocus to txtName: If MultiPage.value = VMT_DASHBOARD_PAGE_MEASURES Then If Controls("txtMeasureName" & mvarlMeasuresControlSets).Enabled Then Controls("fraMeasures").SetFocus Controls("txtMeasureName" & mvarlMeasuresControlSets).SetFocus End If End If