根据userform上列表框中的选择更改数组值

时间:2017-07-05 18:39:28

标签: vba excel-vba excel

我希望能够从运行userform的sub更改数组值。我该怎么做呢?

以下是我的例子:

A = [25, 50, 75, 100]
UserForm1.Show

UserForm1包含一个包含选项1,2或3的列表框 通过选择" 1"," 2,"," 3"或其中的多种组合,我想相应地更改A的值。

If "1" is selected Then
A(0) = 10
If "2" is selected Then
A(1) = 0
If "3" is selected Then
A(2) = 1000

我该如何做到这一点?提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

这是在ListBox事件中测试的。获取lb对象(分配给变量lb.List)的句柄,然后迭代A中的项目,检查是否已选中每个项目。如果选中,则将位置值分配给数组A

数组_Initialize在此声明为模块/用户形式范围变量,并在表单Option Explicit Dim A() Private Sub UserForm_Initialize() 'Assigns initial values to your array: A = Array(25, 50, 75, 100) 'Assigns the default ListBox items: Me.ListBox1.List = Array("1", "2", "3") End Sub Private Sub ListBox1_AfterUpdate() Dim lb As MSForms.ListBox Dim i As Long, v As Long Set lb = Me.ListBox1 '# Modify as needed For i = 0 To lb.ListCount - 1 If lb.Selected(i) Then Select Case lb.List(i) Case "1" v = 10 Case "2" v = 0 Case "3" v = 1000 End Select 'confirm prev & new values for array: MsgBox (A(i) & " will be changed to: " & v) A(i) = v 'Confirm the value in array has changed MsgBox (A(i)) End If Next End Sub 事件期间分配默认/初始值。如果用户在ListBox中进行选择,则会更改这些值。

A

根据初始化ListBox_Change数组的位置/时间,您可以修改此内容并从ListBox_AfterUpdateDim MyDataTable as datatable = GetDT Me.Control.DataBindings.Add(New Binding(Me.BindingProperty, MyDataTable, FieldName, True, DataSourceUpdateMode.OnValidation)) Function GetDT() As DataTable Dim DT As New DataTable Dim i As Integer = 0 DT.Columns.Add(New DataColumn("C1", i.GetType)) DT.Columns(0).AllowDBNull = False Dim R As DataRow = DT.NewRow R.Item(0) = 15 DT.Rows.Add(R) Return DT End Function 事件中调用它,或从其他控件调用它事件程序根据需要。