My macro creates a simple modeless userform that lists all the worksheets as labels and assigns macro to each label to switch the activesheet when user clicks a worksheet name on the userform. Everything is done through vba.
The problem is that the userform doesn't stay on top after macro ends. What is interesting it works when i comment the lines that add code lines to the userform (myForm.codemodule.insertlines).
Did anyone had the same problem before? I really appreciate your help. Thank you! See my macro below:
The problem is that the userform doesn't stay on top after macro ends. What is interesting it works when i comment the lines that add code lines to the userform (myForm.codemodule.insertlines).
Did anyone had the same problem before? I really appreciate your help. Thank you! See my macro below:
Code:
Sub SwitchTab()
Application.VBE.MainWindow.Visible = False
Dim myForm As Object, x As Long, CodeLine As String
Dim NewLabel As MSForms.Label
Application.VBE.MainWindow.Visible = False
Set myForm = ThisWorkbook.VBProject.VBComponents.Add(3) 'vbext_ct_MSForm
With myForm
.Properties("StartUpPosition") = 0 'Manual
.Properties("Left") = 780
.Properties("Caption") = "Switch between Tabs"
'.Properties("Name") = "Switch"
.Properties("Width") = 100
'.Properties("Height") = 12
End With
For x = 1 To ActiveWorkbook.Worksheets.Count
Set NewLabel = myForm.designer.Controls.Add("Forms.Label.1")
myForm.Properties("Height") = 12 * x + 40
With NewLabel
.Name = "Label" & x
.Caption = ActiveWorkbook.Worksheets(x).Name
.Top = 12 * x
.Left = 10
.Width = 80
.Height = 10
.Font.Size = 8
.Font.Name = "Tahoma"
.Font.Underline = True
.ForeColor = &HFF0000 '&H00FF0000&
.MousePointer = fmMousePointerCustom
'.MouseIcon = "C:\Windows\Cursors\hand.cur"
CodeLine = "Private Sub " & NewLabel.Name & "_Click()"
myForm.codemodule.insertlines (x - 1) * 3 + 1, CodeLine
CodeLine = "Activeworkbook.Worksheets(""" & NewLabel.Caption & """).Activate"
myForm.codemodule.insertlines (x - 1) * 3 + 2, CodeLine
myForm.codemodule.insertlines (x - 1) * 3 + 3, "End Sub"
End With
Next
myForm.Properties("ShowModal").Value = False
VBA.UserForms.Add(myForm.Name).Show
End Sub