I am attempting to create a simple programme to consolidate information on Excel via VBA into a user-friendly programme. I am a beginner in VBA, hence do require your kind help in this matter.
First of all, a workbook is comprised of many different worksheets, each one containing different categories of information. The user will click on a button to select which worksheet title is most suitable for their circumstance, before the programme retrieves information within that worksheet. I want to make the programme such that the manager in future can continue to customise the workbook in future by altering the number of worksheets and the programme would respond accordingly.
I have thus decided that I need dynamically created buttons on a userform. My current code in a module goes:
Sub Layer1()
Dim ws As Worksheet
Dim maincats() As Variant
Dim i As Long
ReDim maincats(ThisWorkbook.Sheets.Count)
For Each ws In ThisWorkbook.Sheets
maincats(i) = ws.Range("A1").Value
i = i + 1
Next ws
Dim ub, As Integer
Dim text As String
ub = UBound(maincats) - 1
Dim x As Integer
Dim btn As CommandButton
Dim topPos As Integer
topPos = 100
For x = 0 To ub
Set btn = UserForm1.Controls.Add("Forms.CommandButton.1")
With btn
.Caption = maincats(x)
.Left = 50
.Top = topPos
.Width = 100
.Height = 30
End With
topPos = topPos + 40
Next x
UserForm1.Show
End Sub
The above code appears to suit my elementary needs decently, having creating a userform with the correct number of buttons that correspond to the correct number of worksheets. Now I need to actually link the buttons to the corresponding worksheets, so what can I do in this case? I have attempted to comb through the web for information, but most guides appear to clarify on doing so with buttons already created in the UserForm, which I believe in my case does not apply.
May I know if anyone has any help to offer in this case? Feel free to let me know if you need more clarifications from me! Any help will be greatly appreciated.
Thank you in advance!