真的很纠结这个问题,暂时找到了一个解决方案,但它并不是一个真正令人满意的。我有两个用户表单的工作簿,一个输入数据,一个搜索以前输入的数据和第三个用户表单设计为日期选择器表单,设置为激活指定日期文本框的输入。
单独我没有问题,用户单击文本框和日期选择器表单出现,他们做出选择,关闭日期选择器表单并将日期添加到文本框中。在"输入数据"表单上,我有一个多页,每个页面上都有一个日期选择文本框,在"查找数据"表单上,我有一个搜索单个日期或范围的选项,总共有3个日期选择文本框。
现在我注意到userform1(输入数据)提示运行时错误91 -对象变量或未设置块变量,并且每当我从日期选择器表单中选择日期时,都会在代码中标记userform2的第一行。
然而,我注意到的是,正确的日期仍然被输入到文本框中,因此作为一个修复,我在突出显示的行上方添加了一个"On error goto"行,这使得该操作可以不间断地进行。我注意到的是,现在如果我在userform2上的任何地方输入一个日期(查找数据),然后关闭表单并决定要输入数据,那么userform1上的文本框将包含userform2上先前选择的内容。让我特别困惑的是,UF1的初始化事件在日期文本框中输入当前日期。见下面的代码,有没有更好的方法来写这个?我希望我解释得足够好,如果我能提供更多的细节帮助,请告诉我。
Sub CloseDatePicker(save As Boolean)
If UserForm1.MultiPage1.Value = 0 Then
UserForm1.tbDate.Text = Calendar1.Value
UserForm1.cbMember.SetFocus
ElseIf UserForm1.MultiPage1.Value = 1 Then
UserForm1.tbDate2.Text = Calendar1.Value
UserForm1.cbMember2.SetFocus
End If
On Error GoTo dpexit
If UserForm2.ActiveControl.Name = "TextBox1" Then
UserForm2.TextBox1.Text = Calendar1.Value
End If
If UserForm2.ActiveControl.Name = "TextBox2" Then
UserForm2.TextBox2.Text = Calendar1.Value
ElseIf UserForm2.ActiveControl.Name = "TextBox3" Then
UserForm2.TextBox3.Text = Calendar1.Value
End If
dpexit:
Me.Hide
End Sub
就在门外,我看到你的代码的第一个问题是你试图改变一个文本框的值与.Text
属性。我个人从来没有运气使用.Text
设置值,因为它始终抛出Err:91
。相反,我发现使用.Value
更好。
Sub CloseDatePicker(save As Boolean)
If UserForm1.MultiPage1.Value = 0 Then
UserForm1.tbDate.Value = Calendar1.Value
UserForm1.cbMember.SetFocus
ElseIf UserForm1.MultiPage1.Value = 1 Then
UserForm1.tbDate2.Value = Calendar1.Value
UserForm1.cbMember2.SetFocus
End If
' On Error GoTo dpexit 'disabled this for you to test your code
If UserForm2.ActiveControl.Name = "TextBox1" Then
UserForm2.TextBox1.Value = Calendar1.Value
End If
If UserForm2.ActiveControl.Name = "TextBox2" Then
UserForm2.TextBox2.Value = Calendar1.Value
ElseIf UserForm2.ActiveControl.Name = "TextBox3" Then
UserForm2.TextBox3.Value = Calendar1.Value
End If
dpexit:
Me.Hide
End Sub