0

I am making a userform for making a order in a pub for example.

So my intention is whenever I click on a commandbutton, it has to appear in my listbox. SO when I click on Cola

There will be in my listbox: Cola 1

The next time I click on cola, there should be Cola 2 but that doesn't work.

Here is my code:

 Private Sub CommandButton1_Click()


With Sheets(3)
        .Cells(Me.ComboBox1.ListIndex + 2, 2) = .Cells(Me.ComboBox1.ListIndex + 2, 2) + 1
End With



Dim i As Integer
i = 1
With Me.ListBox1
    Me.ListBox1.ColumnCount = 2
    Me.ListBox1.ColumnWidths = "60;60"
    .AddItem
    .List(0, 0) = CommandButton1.Caption
    .List(0, 1) = i
End With

   i = i + 1


End Sub

But he doesn't seem to remember the value of i And so when I click a second time on Cola, nothing changes.

Thanks in advance!

Ewout
  • 3
  • 1

1 Answers1

0

i is a procedure level variable - it only persists until the procedure runs its course. When Private Sub CommandButton1_Click() ends then i effectively ceases to exist.

Declare i in a module as Global

Global i as Long 'Long doesn't have much more overhead than Integer

and it will persist after your code runs

You also need to loose the

Dim i As Integer i = 1

because that is resetting i every time you click the button.

Mark Fitzgerald
  • 3,048
  • 3
  • 24
  • 29
  • `Global` is [old an unnecessary](http://stackoverflow.com/a/3815797/11683). Promoting a local variable to a broader scope is also bad. The correct thing is to declare the variable inside the procedure as `Static`. – GSerg Nov 02 '14 at 11:59