Excel VBA用户表单,用于显示所选的工作表

时间:2017-04-10 05:42:18

标签: vba excel-vba excel

我创建了一个userform,它有一个列表框(ListBox1),列出了工作表名称,我可以双击列表,它将带我到那个工作表。我有一个后退按钮(CommandButton2),当我点击后退按钮时,它将带我到上一个选定的工作表。 我想链接我的列表框和后退按钮,以便当我单击后退按钮时,我的列表框(ListBox1)应该突出显示我的后退按钮(CommandButton2)所指向的工作表。

请在下面找到我的代码:

Private Sub UserForm_Initialize()

Dim Sh As Worksheet

'for each loop the add visible sheets

For Each Sh In ActiveWorkbook.Sheets

'add sheets to the listbox

Me.ListBox1.AddItem Sh.Name

Next Sh

End Sub

Private Sub ListBox1_DblClick(ByVal Cancel As MSForms.ReturnBoolean)

'declare the variables

' modifed code for ListBox double-click event, store the sheet name before switching to the selected item

Dim i As Long

LastSelectedSht = ActiveSheet.Name ' <-- save the current active sheet before selecting a new one

For i = 0 To ListBox1.ListCount - 1

If ListBox1.Selected(i) Then

     Worksheets(ListBox1.List(i)).Activate

End If

Next i

End Sub


Private Sub CommandButton2_Click()

Dim TmpSht As String

TmpSht = ActiveSheet.Name ' <-- save the current active sheet

' select the previous sheet (stored in LastSelectedSht)

If LastSelectedSht = "" Then

    MsgBox "Error, no sheet stored , is it your first time running ? "

Else

    Sheets(LastSelectedSht).Select

End If

LastSelectedSht = TmpSht ' <-- use the temp variable to store the latest active sheet

' reset the userform

Unload Me

frmNavigation.Show

End Sub

2 个答案:

答案 0 :(得分:2)

不需要那些循环来寻找所选项目,你可以简化一下如下:

Option Explicit

Dim LastSelectedSht As String '<--| use as UserForm scoped variable to store the name of "last" sheet selected

Private Sub UserForm_Initialize()
    Dim Sh As Worksheet

    With Me.ListBox1
        'for each loop the add visible sheets
        For Each Sh In ActiveWorkbook.Sheets
            .AddItem Sh.Name 'add sheets names to the listbox
        Next Sh
        LastSelectedSht = ActiveSheet.Name ' <-- store the currently active sheet name as the "last" one
        .Value = LastSelectedSht '<--| initialize listbox selection with the currently active sheet name
    End With
End Sub

Private Sub ListBox1_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
    ' modifed code for ListBox double-click event, store the sheet name before switching to the selected item
    LastSelectedSht = ActiveSheet.Name
    Worksheets(ListBox1.Value).Activate '<--| activate the sheet whose name has been dblclicked
End Sub

Private Sub CommandButton2_Click()
    Sheets(LastSelectedSht).Activate
    Me.ListBox1.Value = LastSelectedSht

    ' reset the userform

    Unload Me
    frmNavigation.Show
End Sub

答案 1 :(得分:0)

此子将更改列表框中的选定项目。

Private Sub SetListBox(Lbx As MSForms.ListBox, _
                       Itm As String)
    Dim i As Integer

    With Lbx
        For i = 0 To .ListCount - 1
            .Selected(i) = Not CBool(StrComp(.List(i), Itm))
        Next i
    End With
End Sub

从你的程序中调用它,用一行代码激活上一个工作表。

SetListBox ListBox1, TmpSht

确保TmpSht在您拨打电话时保留新激活的工作表的名称,或者传递该工作表的名称而不是TmpSht。