CommandButton_Click不记得我的变量VBA EXCEL

时间:2014-11-02 11:16:33

标签: excel vba

我正在制作用户表单,例如在酒吧订购。

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

我的列表框中会有:可乐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

但他似乎并不记得我的价值 因此,当我第二次点击Cola时,没有任何变化。

提前致谢!

1 个答案:

答案 0 :(得分: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