Excel VBA Course
Excel VBA Course - From Beginner to Expert

200+ Video Lessons
50+ Hours of Video
200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

View Course

populate new names in listbox on userform

1

Hello,

I need help to adapt code in listbox2

my problem when there are new names in first sheet and they are not existed in second sheet will nt show in listbox 2

the listbox2 merge amounts for data showing in listbox1 for columns 5,6 based on name column 2 and show result in listbox2 when select items from combobox1 or write dates in textboxes.

ex: omar=2000+580000+1000+1000=584000

and when there is name in balance first of duration sheet then should add to amount where is merged and if the amount is plus then when add to amount where is merged in listbox should be in debit  

ex:mariam =-5000-(100+500000)=505100

I put the picture in third sheet how show new names marked  in listbox2

Private Sub LB2()
    sn = ListBox1.List
    Set dic = CreateObject("scripting.dictionary")
    With ListBox1
        For i = 1 To .ListCount - 1
            x0 = dic.Item(.List(i, 1))
        Next
    End With
    ReDim Total(1 To dic.Count + 1, 1 To 5)
    myarr = Array("Item", "Name", "Debit", "Credit", "Balance")
    For i = 0 To 4
        Total(1, i + 1) = myarr(i)
    Next
    For i = 1 To dic.Count
        Total(i + 1, 1) = i: Total(i + 1, 2) = dic.keys()(i - 1)
    Next
    For i = 0 To dic.Count - 1
        For ii = 1 To UBound(sn)
            If sn(ii, 1) = dic.keys()(i) Then
                Total(i + 2, 3) = Total(i + 2, 3) + sn(ii, 4)
                Total(i + 2, 4) = Total(i + 2, 4) + sn(ii, 5)
            End If
        Next
        With Worksheet____1
            wRow = Application.Match(dic.keys()(i), .Columns(2), 0)
            If Not IsError(wRow) Then
                If .Cells(wRow, 4) > 0 Then
                    Total(i + 2, 3) = Total(i + 2, 3) + .Cells(wRow, 4)
                Else
                    Total(i + 2, 4) = Total(i + 2, 4) + (-1 * .Cells(wRow, 4))
                End If
            End If
        End With
    Next
    For i = 2 To UBound(Total)
        Total(i, 5) = Total(i, 3) - Total(i, 4)
    Next
    With ListBox2
        .List = Total
        .AddItem
        .List(.ListCount - 1, 0) = "TOTAL"
        .List(.ListCount - 1, 2) = Application.Sum(Application.Index(Total, 0, 3))
        .List(.ListCount - 1, 3) = Application.Sum(Application.Index(Total, 0, 4))
        .List(.ListCount - 1, 4) = Application.Sum(Application.Index(Total, 0, 5))
        For i = 0 To .ListCount - 1
            For j = 2 To 4
                .List(i, j) = Format(.List(i, j), "#,##0.00")
            Next
        Next
    End With
End Sub

thanks

Answer
Discuss

Discussion

Tamer, please see Revison #6 and second file in my Answer- hopefully this gives you a fully-working solution.
John_Ru (rep: 6762) Sep 4, '25 at 11:04 am
Add to Discussion

Answers

0
Selected Answer

Hi Tamer 

Revision #4 (Replacement Answer) 01 September 2025

On checking your code again, I realised that the problem is not with Private Sub LB2() -which populates ListBox 2 of UserForm1) but with the procedure GetData()....

In the attached revised file, I've modified the code as follows (with comments to say broadly what happens and where the error was  / how I corrected it). Please see the changes in bold:

Private  
    Dim a, i As Long, ii As Long, rng As Range, x, n As Long, myList, temp
    Dim myName As String, Dates(1 To 2), flg As Boolean

    ' new loop counter for CB1=all
    Dim p As Long

    For i = 4 To 6
        Me("textbox" & i) = 0
    Next
    myName = Me.ComboBox1.Value
    For i = 1 To 2
        If Me("textbox" & i) <> "" Then
            If Me("TextBox" & i) Like "##/##/####" Then
                x = Split(Me("textbox" & i), "/")
                Dates(i) = DateSerial(x(2), x(1), x(0))
            Else
                MsgBox "Date in " & IIf(i = 1, "DateFrom", "DateTo") & " is not valid": Exit Sub
            End If
        End If
    Next
    Set rng = Sheets("balance first of  duration").Cells(1).CurrentRegion
    a = Sheets("sheet1").Cells(1).CurrentRegion.Value

    ReDim myList(1 To UBound(a, 1) + 1)

        ' this section checks "balance first...."
        If (myName <> "") * (myName <> "all") Then
            x = Application.Match(myName, rng.Columns(2), 0)
            If IsNumeric(x) Then
                Me.TextBox3 = rng(x, 4)
                temp = Evaluate("{""" & Format$(rng(x, 1), "yyyy/m/d") & """,""" & _
                    rng(x, 2) & """,""" & rng(x, 3) & ""","""","""","""",""" & rng(x, 4) & """}")
                n = n + 1: myList(n) = temp
            Else
                Me.TextBox3 = 0
            End If

            ' ### but this portion failed to collect the balance details when "all" (so it's commented out)
'           Else
'
'            Me.TextBox3 = Application.Sum(rng.Columns(4))
'            temp = Evaluate("{""" & Format$(rng(2, 1), "yyyy/m/d") & ""","""","""","""","""","""",""" & _
'                Application.Sum(rng.Columns(4)) & """}")
'            n = n + 1: myList(n) = temp

            ' ### replaced with this portion...
            Else
            ' gather all balances
            For p = 2 To rng.Rows.Count
                Me.TextBox3 = rng(p, 4)
                temp = Evaluate("{""" & Format$(rng(p, 1), "yyyy/m/d") & """,""" & _
                    rng(p, 2) & """,""" & rng(p, 3) & ""","""","""","""",""" & rng(p, 4) & """}")
                n = n + 1: myList(n) = temp
            Next p
        End If

        ' this checks then entries in "sheet1"
        For i = 2 To UBound(a, 1)
            If (myName <> "") * (myName <> "all") Then
                flg = a(i, 2) = myName
            ElseIf (myName = "") + (myName = "all") Then

                flg = True

            End If

            If IsDate(Dates(1)) Then flg = flg * (a(i, 1) >= Dates(1)) Else flg = flg * True
            If IsDate(Dates(2)) Then flg = flg * (a(i, 1) <= Dates(2)) Else flg = flg * True
            If flg Then

                n = n + 1

                x = Application.Index(a, i, Array(1, 2, 3, 4, 5, 6, 6))
                Me.TextBox4 = Val(Me.TextBox4) + x(5)
                Me.TextBox5 = Val(Me.TextBox5) + x(6)
                If n > 1 Then
                    temp = myList(n - 1)
                    x(UBound(x)) = temp(UBound(temp))
                Else
                    x(UBound(x)) = 0
                End If
                x(UBound(x)) = x(UBound(x)) + x(UBound(x) - 2) - x(UBound(x) - 1)
                ReDim Preserve myList(1 To 51)

                myList(n) = x
            End If
        Next i

    Me.ListBox1.Clear
    If n = 0 Then Exit Sub
    Me.ListBox1.ColumnCount = 7
    ReDim Preserve myList(1 To n)
    Me.TextBox6 = Val(Me.TextBox3) + Val(Me.TextBox4) - Val(Me.TextBox5)
    If n = 1 Then
        Me.ListBox1.Column = myList(n)
    Else
        Me.ListBox1.List = Application.Index(myList, 0, 0)
    End If
    With Sheets("result1")
        .[n3] = Me.ComboBox1
        .[o4:p4] = Array(Dates(1), Dates(2))
    End With
    With ListBox1
        .ColumnCount = 7    '<---- Change to 18??????
        .ColumnWidths = "65;60;60;50;50;50;50"    ' modified
    End With
    LB2
End Sub

Revision #5 03 September 2025

A further revision was needed to Sub LB2 to correct the output in ListBox2, this time reversing changes I made earlier- see comments and items in bold below

Private Sub LB2()
    sn = ListBox1.List
    Set dic = CreateObject("scripting.dictionary")
    With ListBox1
        ' corrected- was revised to: For i = 1 To .ListCount
        For i = 0 To .ListCount - 1
            ' corrected- was revised to: x0 = dic.Item(.List(i - 1, 1))
            x0 = dic.Item(.List(i, 1))
        Next
    End With

Now the code gives the outcomes shown on your worksheet result1 (by clicking the button "Launch form" and picking "all" under the NAMES dropdown) and individual name selections give correct balances.

Revision #6 04 September 2025

The solution above gives correct results in ListBox2 but confusing (and incorrect) balances in ListBox1. In the SECOND file attached, the code has a quick fix to suppress line balances in ListBox1, see changes in bold to this portion of Sub GetData():.

<< existing code omitted>>
            If IsDate(Dates(1)) Then flg = flg * (a(i, 1) >= Dates(1)) Else flg = flg * True
            If IsDate(Dates(2)) Then flg = flg * (a(i, 1) <= Dates(2)) Else flg = flg * True
            If flg Then

                n = n + 1

                x = Application.Index(a, i, Array(1, 2, 3, 4, 5, 6, 6))
                Me.TextBox4 = Val(Me.TextBox4) + x(5)
                Me.TextBox5 = Val(Me.TextBox5) + x(6)
                ' to suppress line balances, skip this...
'                If n > 1 Then
'                    temp = myList(n - 1)
'                    x(UBound(x)) = temp(UBound(temp))
'                Else
'                    x(UBound(x)) = 0
'                End If
'                x(UBound(x)) = x(UBound(x)) + x(UBound(x) - 2) - x(UBound(x) - 1)
                '... but use this
                x(UBound(x)) = ""

                ReDim Preserve myList(1 To 51)

                myList(n) = x
            End If
        Next i
<< existing code omitted>>

Hope this solves your problem. If so, please be sure to mark this Answer as Selected.

Discuss

Discussion

thanks John for your trying.
unfortunately I don't see Amer and Karrem names in listbox2 when select all!
tamer (rep: 4) Aug 28, '25 at 3:53 am
Hi again Tamer. I didn't test for All - will try in a bit and get back to you. Please confirm that indivudual results display correctly. 
John_Ru (rep: 6762) Aug 28, '25 at 5:59 am
no need show first row is existed in listbox1  and show zero in listbox2  so this is not important for me to show it .
tamer (rep: 4) Aug 28, '25 at 6:33 am
Apologies Tamer- although the code in my Answer was correct, I see that the file was NOT (so individual results for Amer and Karrem did NOT show)- I've replaced that file (with ...v0_b.xlsm) now.   That does NOT fix the problem of "all" however so I'll need to look again later.
John_Ru (rep: 6762) Aug 28, '25 at 6:44 am
Sorry but I'm not sure what you mean by your comment "no need show first row is existed in listbox1  and show zero in listbox2  so this is not important for me to show it "
John_Ru (rep: 6762) Aug 28, '25 at 6:49 am
just look at listbox2 will show first row contains zero I suppose brings from first row in listbox1. 
tamer (rep: 4) Aug 28, '25 at 7:25 am
Thanks. Please see Revision #2 28 August 2025 to my Answer and the SECOND file attached to that. Hopefully it all works well now. Don't forget to mark my Answer as Selected if that works for you. Thanks in advance.
John_Ru (rep: 6762) Aug 28, '25 at 5:36 pm
thanks again,
but unfortunately there names are missed in listbox1,listbox2 like 
khalid,mohmoud !
tamer (rep: 4) Aug 29, '25 at 12:11 pm
Tamer, please see my replacement Answer (and revised file)
John_Ru (rep: 6762) Sep 1, '25 at 1:46 pm
thanks 
really great , but not completely because I see the last column in listbox1 will calculate incorrectly . when show the balances for names from balance first of  duration sheet    then should sum all of balances  to be -7500 and add to next row contains debit and subtract from credit . 
see in row 8 in listbox1  in last column should be -7500+150000-1000=141500   but in your attachment  show 154000
in original code show -7500 in first row (total balance names) 
but I notice the last balance  in row 7 just deal with it and ignore rest of balances before row7.
in your case calculate like this 5000+150000-1000=154000 this is wrong.
sorry about my english is bad because not primary language in my country
tamer (rep: 4) Sep 2, '25 at 4:19 am
Thanks for comment, Tamer. I'm busy today so will try to check tomorrow. I understand about your English but will try to understand.

In the meantime, please check - I thought that the revised code produced the same as your example in result1.

Note too that the Forum exists to help you by answering questions - it isn't our job to fix your code but I guess you didn't create it, right? What is your experience of VBA?
John_Ru (rep: 6762) Sep 2, '25 at 6:24 am
Note too that the Forum exists to help you by answering questions
I apprecaite that.
it isn't our job to fix your code
I expect when adapt code doesn't effect calculation.
but I guess you didn't create it, right?
yes
any way  thanks for your time.
tamer (rep: 4) Sep 2, '25 at 7:06 am
Did you check against result1? (I can't since I only have the mobile (cell) phone version of Excel today).

Note that I will try to reply tomorrow anyway 
John_Ru (rep: 6762) Sep 2, '25 at 7:13 am
Did you check against result1?
yes show as the pictur without any problem .
tamer (rep: 4) Sep 2, '25 at 7:33 am
Thanks. It feels like I got you the result you wanted (using same calculations) and so answered your Question.

I'll look tomorrow and if I can fix this new additional requirement fairly quickly, I will 
John_Ru (rep: 6762) Sep 2, '25 at 7:52 am
Tamer, please see Revision #5 03 September 2025 and the latest file. This should all work well now- if so, please mark this Answer as Selected (I spent quite a bit of time fixing this and "Selection"  of my Answer is my only reward).
John_Ru (rep: 6762) Sep 3, '25 at 10:07 am
I spent quite a bit of time fixing this
much appreciated that and it's difficult to find person spend much time to solve and help members.
This should all work well now
I don't think so ,sorry I said that !
I see the same result in previous   attached file .
tamer (rep: 4) Sep 3, '25 at 10:20 am
Tamer, sorry but I was concentrating on getting ListBox2 correct (and not looking at the detail in LB1..

I spent another hour  majing one trying to fix your file but hit another problem. Accordingly I don't want to waste any more of my time trying to help you- sorry!
John_Ru (rep: 6762) Sep 3, '25 at 11:49 am
I except when adapt code  just for listbox2 but seem to matther complex than what I think.
anyway john I will depends on listbox2  because  this is the most important 
listbox1 just causes confusing when the  user  look at it and calculation will be wrong.
thanks you so much for your effort and help.
tamer (rep: 4) Sep 3, '25 at 3:50 pm
Thanks for selecting my Answer, Tamer. Sorry I couldn't fix all the problems but the code was too interdependent to fix easily. 
John_Ru (rep: 6762) Sep 4, '25 at 1:29 am
@Tamer - please see Revision #6 04 September 2025 to My Answer (and the second file). Thsi removes the confusion uou mentioed above. No need to Select my Answer- you already did, thanks!

@Willie - thanks for the vote (I'm guessing it was you but respect your anonimity!)
John_Ru (rep: 6762) Sep 4, '25 at 11:02 am
thanks John again ,
but I note you delete calaculation balances  in last column in listbox 1
just show balances in last column based on balance first of duration sheet and ignore calculation for data on sheet1.
tamer (rep: 4) Sep 5, '25 at 2:46 pm
Hi Tamer. It was to save (my) time, so a quick fix from me. LB1 now shows the opening balance plus subsequent transactions while LB2 shows the result (combination) of those.

You can use that or get someone else to fix it (but you may need to pay). Ir you could learn VBA and fix it yourself.

The choice is no effort on your part or some. 
John_Ru (rep: 6762) Sep 6, '25 at 6:06 pm
don't worry john .  I realized to adapt this project  is not easy ,but you gave me two files and two choices  and it's ok. thank you so much for your time and help.
tamer (rep: 4) Sep 7, '25 at 7:46 am
Happy to help, Tamer. Hope you find a way forward. 
John_Ru (rep: 6762) Sep 7, '25 at 8:37 am
Add to Discussion


Answer the Question

You must create an account to use the forum. Create an Account or Login