2014-11-02 71 views
0

我正在制作一个用户窗体,例如在一个酒吧里下订单。CommandButton_Click不记得我的变量VBA EXCEL

所以我的意图是每当我点击一个命令按钮,它必须出现在我的列表框中。 所以当我点击可乐

会有我的列表框:下一次我点击可乐可乐1

,应该有可乐2 但不起作用。

这里是我的代码:

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 

但他似乎并不记得我 所以当我点击第二次上可乐,没有什么变化的值。

在此先感谢!

回答

0

i是一个过程级别变量 - 它只会持续到该过程运行其过程。当Private Sub CommandButton1_Click()结束时,i有效地不复存在。

申报i模块作为Global

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

和你的代码后,会持续运行

您还需要宽松的

Dim i As Integer i = 1

,因为这是每次重置i你点击按钮。

+0

'全球'是[旧的不必要](http://stackoverflow.com/a/3815797/11683)。将局部变量推广到更广泛的范围也是不好的。正确的做法是将过程中的变量声明为'Static'。 – GSerg 2014-11-02 11:59:00