我創建了一個用戶窗體,其中有一個列表框(ListBox1),它列出了工作表名稱,我可以在列表中雙擊,它將帶我到該工作表。我有一個後退按鈕(CommandButton2),當我點擊後退按鈕時,它會將我帶到上一個選定的工作表。 我想鏈接我的列表框和後退按鈕,這樣當我點擊後退按鈕時,我的列表框(ListBox1)應該突出顯示我的後退按鈕(CommandButton2)所指向的工作表。Excel VBA用戶窗體顯示選中的工作表
請找我下面的代碼:
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
@astha:上面的代碼是您在用戶窗體代碼窗格中所需的代碼/顯示功能的所有代碼。如果您需要幫助,只需詢問 – user3598756
這是我完成它的方式,並且足夠動態以處理添加的任何工作表。 – Wowdude
謝謝@Wowdude。現在讓我們等待astha的反饋! – user3598756