2017-04-09 103 views
0

我創建了一個用戶窗體frmNavigation,它具有一個ListBox1,它將列出工作簿中的所有工作表,並且可以雙擊任何工作表列表框並轉到該表單。在excel vba用戶窗體中創建一個後退按鈕,轉到上一個活動窗體

現在,因爲我有近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 

回答

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 
+0

它給我的錯誤爲下標超出範圍就行表(LastSelectedSht)。選擇 – astha

+0

私人小組UserForm_Initialize() 昏暗SH作爲變 「每個循環的新增可見片 對於每個sh放在ActiveWorkbook.Sheets 「添加片材到列表框 Me.ListBox1.AddItem Sh.Name 接着噓 – astha

+0

@astha什麼時候?你第一次加載你的表單? –

相關問題