使用VBA用户表单选择多个工作表上的范围 - 工作表更改回原始活动工作表

时间:2017-05-15 16:44:37

标签: excel-vba userform vba excel

我有一个具有多个RefEdit控件的userform。我需要用户从多个工作表中选择范围,并且必须先完成用户表单才能运行其余代码。

问题:活动表是" Sheet1"何时启动用户表单。每次我选择" Sheet2"然后单击进入下一个RefEdit,可见的Excel工作表返回到" Sheet1"。我希望工作表保留在" Sheet2",因为在工作表之间点击会显着增加选择数据所需的时间。

因为我需要在继续使用代码之前完成用户表单,所以使用" vbModeless"似乎不起作用。

我尝试逐步完成看似相关的用户表单事件,但在我输入RefEdit,选择数据或离开RefEdit时没有激活。

提前感谢您的帮助!

编辑:使用回复中的一些输入并进行更多研究我认为我已经找到了问题并解决了问题。

RefEdit事件,例如更改或退出(我认为我尝试了所有这些)在控件中发生更改时似乎不会触发。因此,当我更改控件时,我无法编写代码来操作活动表。此处找到一种解决方法:http://peltiertech.com/refedit-control-alternative/使用文本框和输入框来模拟RefEdit控件,并在更改时实际触发!代码如下。添加其他" RefEdit"控件应该为每个控件重复Userform_Initialize事件中的代码,然后添加另一个TextBox1_DropButtonClick并将TextBox1更新为新控件的名称。在控件更新工作簿时使用,跳转到上一个活动表,然后返回所需的活动表。不像我想的那么顺利,但比它好得多。

代码:

Private Sub CancelButton_Click()
    Unload Me
    End
End Sub
Private Sub OKButton_Click()
    UserForm1.Hide
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    End
End Sub
Private Sub UserForm_Initialize()
    Me.TextBox1.DropButtonStyle = fmDropButtonStyleReduce
    Me.TextBox1.ShowDropButtonWhen = fmShowDropButtonWhenAlways
End Sub
Private Sub TextBox1_DropButtonClick()
    Dim ASheet As String ' Active sheet

    Me.Hide

    'Use input box to allow user to select a range
        On Error Resume Next
            Me.TextBox1.Value = Application.InputBox("Select the range containing your data", _
                    "Select Chart Data", Me.TextBox1.Text, Me.Left + 2, _
                    Me.Top - 86, , , 0)
        On Error GoTo 0

    'Check if there is a sheet name - if the range selected is on the activesheet the output of the inputbox doesn't have a sheet name.
        If InStr(1, Me.TextBox1.Value, "!", vbTextCompare) > 0 Then ' there is a sheet name
            ASheet = Replace(Split(Me.TextBox1.Value, "!")(0), "=", "") ' extract sheet name
        Else ' there is no sheet name
            Me.TextBox1.Value = "=" & ActiveSheet.Name & "!" & Replace(Me.TextBox1.Value, "=", "") ' add active sheet name to inputbox output
            ASheet = ActiveSheet.Name
        End If

    Worksheets(ASheet).Activate ' set the active sheet

    Me.Show

End Sub

2 个答案:

答案 0 :(得分:1)

你有没有尝试过这么简单的事情:

表( “Sheet 2中”)。选择

在表单代码的开头某处?

由于您尚未发布代码,因此很难提供一个好的答案。 希望这有点帮助:))

答案 1 :(得分:0)

此表格模块适用于我。

Private Sub CommandButton1_Click() 'Cancel Button
Unload Me
End Sub

Private Sub CommandButton2_Click()  'GO Button
Dim newSheet As Worksheet

abc = Split(RefEdit1.Value, "!")
cbn = abc(0)
Unload Me
Set newSheet = Worksheets(abc(0))
newSheet.Activate
End Sub
相关问题