在excel vba userform中创建一个后退按钮,转到上一个活动工作表

时间:2017-04-09 17:56:45

标签: vba excel-vba excel

我创建了一个frmNavigation的用户形式ListBox1,它会列出我工作簿中的所有工作表,我可以双击列表框中列出的任何工作表,然后转到片材。

现在我有近50个工作表,所以我从ListBox1中出现的列表中双击并转到该表,但现在我想要一个后退按钮" CommandButton2"这样它就可以带我回到我之前的活动表。

我创建了一个代码,但它无法正常工作。

Private Sub CommandButton2_Click()

Application.ScreenUpdating = False

Dim i As Integer, Sht As String

'for loop
For i = 0 To ListBox1.ListCount - 1
    'get the name of the selected sheet
    If ListBox1.Selected(i) = True Then
        Sht = ListBox1.List(i - 1)
    End If
Next i

'select the sheet
Sheets(Sht).Select

'reset the userform
Unload Me
frmNavigation.Show

End Sub

1 个答案:

答案 0 :(得分:0)

尝试下面的代码,我不知道如何解释下面代码的逻辑,我最好在代码注释中描述它。

我还修改了ListBox1_DblClick代码事件,以便在ActiveSheet新工作表之前保存最新的Select

<强>代码

Option Explicit

Dim LastSelectedSht As String ' Variable at module level, to store the name of the last selected sheet

'===================================================================

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

'===================================================================

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

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 UserForm_Activate()

Dim ws As Worksheet

For Each ws In ThisWorkbook.Sheets
    Me.ListBox1.AddItem ws.Name
Next ws

End Sub