Excel 隐藏用户表单而不终止子例程
我有一个UserForm,用户可以从中选择在活动工作表中进行选择,该工作表将在代码中进一步使用Excel 隐藏用户表单而不终止子例程,excel,vba,userform,Excel,Vba,Userform,我有一个UserForm,用户可以从中选择在活动工作表中进行选择,该工作表将在代码中进一步使用 Private Sub CommandButton1_Click() Dim results As String Me.Hide results = get_range_from_selection() Me.Show TextBox.Text = results End Sub Public Function get_range_from_se
Private Sub CommandButton1_Click()
Dim results As String
Me.Hide
results = get_range_from_selection()
Me.Show
TextBox.Text = results
End Sub
Public Function get_range_from_selection() As String
Dim selection As Range
Set selection = Application.InputBox("Select rows.", "Select Rows", Type:=8)
get_range_from_selection = selection.Address
End Function
但是,在单个屏幕上,用户表单会妨碍工作表的工作,因此很难进行选择,因此我需要以某种方式隐藏/最小化表单
我尝试过使用UserForm.Hide方法,但问题是,尽管UserForm保留了textboks值等,但它似乎终止了button _Click()事件子例程,该子例程首先使用上述代码调用函数。该函数一直执行到结束,但是_Click()子例程在UserForm中根据选择执行操作时终止于UserForm.Show
我尝试将.Hide/.Show放在_Click()子例程和被调用函数中,但结果是一样的。它的行为应该是这样的吗?有什么解决方法或其他方法可以尝试吗?我建议您可以在您的用户表单中尝试以下代码。我假设代码属于一个命令按钮,需要单击该按钮才能选择范围
Private Sub CommandButton1_Click()
Dim rg As Range
Me.Hide
Set rg = Application.InputBox("Select rows.", "Select Rows", Type:=8)
' Be careful as the user could select a range from a different sheet
' or even a different workbook.
If rg.Parent Is ActiveSheet Then
rg.Select
End If
Me.Show
End Sub
您可能使用了类似于Userform1.Hide
的东西,而不是Me.Hide
,这通常会导致问题,请看一看或看一看
更新:您也可以像那样“隐藏”表单
Private Sub CommandButton1_Click()
Dim rg As Range
Dim fHeight As Double
Dim fWidth As Double
fHeight = Me.Height
fWidth = Me.Width
Me.Height = 0
Me.Width = 0
Set rg = Application.InputBox("Select rows.", "Select Rows", Type:=8)
' Be careful as the user could select a range from a different sheet
If rg.Parent Is ActiveSheet Then
rg.Select
End If
Me.Height = fHeight
Me.Width = fWidth
End Sub
在这种情况下,Me.Show
不会“停止”代码
更新2:根据更新后的帖子,您可以在用户表单中尝试以下代码
Option Explicit
Dim fHeight As Double
Dim fWidth As Double
Private Sub CommandButton1_Click()
Dim results As String
meHide
results = get_range_from_selection()
meShow
TextBox.Text = results
End Sub
Private Function meHide()
fHeight = Me.Height
fWidth = Me.Width
Me.Height = 0
Me.Width = 0
End Function
Private Function meShow()
Me.Height = fHeight
Me.Width = fWidth
End Function
Public Function get_range_from_selection() As String
Dim selection As Range
Set selection = Application.InputBox("Select rows.", "Select Rows", Type:=8)
get_range_from_selection = selection.Address
End Function
不要使用Application.Input,而是在userform上使用RefEdit控件?请参阅下面的建议。您是正确的,代码属于命令按钮,但是,选择代码本身位于从命令按钮代码调用的另一个函数中,我只是将范围返回到_Click()代码。我试着用我.Hide代替.Hide,但结果是一样的。_Click()代码终止于Me.Show。然后您应该相应地编辑您的帖子并添加更多信息和代码,因为我的理解是,用户应该选择一个范围,代码应该进入活动选择。@norsemanGrey您是否尝试过
Me.Visible=True
?或者更好的方法是使用RefEdit控件自动折叠表单?是的,RefEdit控件将自动折叠表单,但另一方面,它将返回字符串而不是范围,因此需要验证输入。在我的建议中,仍然需要检查是否单击了cancel
。我认为调整表单大小对我来说是可行的@GSerg我尝试了Me.Visible,但似乎遇到了编译错误:“函数标记为受限或使用了Visual Basic不支持的类型”