I have a small userform with 1 combobox, 2 textbox and 1 command button. Image is attached.
Also the image of worksheet is attached below.

Upon Initialization of Userform, combobox is populated with account heads listed in Table1.
Selection of item from combobox will populate the textbox with Account Code listed in Table1.
Group Head textbox will be entered manually.
Below is my code...
Private Sub ComboBox1_Change()
Dim ws As Worksheet, tbl As ListObject, rng As Range, cmb As ComboBox
Dim accountcode As String, rng1 As Range
Set ws = Sheets("Sheet1")
Set tbl = ws.ListObjects("Table1")
Set rng = tbl.ListColumns(1).DataBodyRange
Set rng1 = tbl.ListColumns(2).DataBodyRange
Me.TextBox1.Value = Application.WorksheetFunction.Index(rng, Application.WorksheetFunction.Match(Me.ComboBox1.Value, rng1, 0))
End Sub
Private Sub CommandButton1_Click()
Dim ws As Worksheet, tbl As ListObject, row As ListRow
Set ws = Sheets("Sheet1")
Set tbl = ws.ListObjects("Table2")
Set row = tbl.ListRows.Add
prefix = Me.TextBox1.Value & "-"
Dim NextNum As Long
Dim LastRow As Long, lRow As Long
Dim myArr() As Long
With Sheets("Sheet1")
'Find Last Row in Group Head Code Column
LastRow = .Cells(.Rows.Count, "E").End(xlUp).row
ReDim myArr(1 To LastRow)
' read all cells contents and convert them to array of numbers
For lRow = 5 To LastRow
If Mid(.Cells(lRow, 5), 4) <> "" Then
myArr(lRow) = CLng(Mid(.Cells(lRow, 5), 4))
End If
Next lRow
' find maximum value in array
NextNum = WorksheetFunction.Max(myArr)
End With
row.Range(1, 1).Value = Me.ComboBox1.Value
row.Range(1, 2).Value = prefix & NextNum + 1
row.Range(1, 3).Value = Me.TextBox2.Value
End Sub
Private Sub UserForm_Initialize()
Dim ws As Worksheet, tbl As ListObject, rng As Range, cmb As ComboBox
Set ws = Sheets("Sheet1")
Set tbl = ws.ListObjects("Table1")
Set rng = tbl.ListColumns(2).DataBodyRange
Set cmb = Me.ComboBox1
For Each rng In rng
cmb.AddItem rng.Value
Next rng
End Sub
The command button reads the value in Table 2, COlumn and 2, Generate the serial number and post the values in the Table.
What i want with the command button is, if i select any other head from the combobox, the code should read the value associated with that prefix and then generate the next serial number. Currently it is not reading the prefix.
Kindly advise what changes need to be made in my command button code to achieve this.
Thanks Salman
ComboBoxtext is different from that which was previously held in theComboBoxsince the last time the user clicked theCommandButton; if so, then generate a new code based on the currentComboBoxtext and a number incremented by one from the last code with the same prefix. Is that correct?