@[TOC]VBA学习1.VBA的字典定义和python一样都是键值对,键唯一
在第一次创建字典时,要加入字典的.dll文件
2.把sheet2里的AB列数据取出来作为数组的值,
把其中的B列 类别加入字典里
最后把字典的键放入listbox的list里
代码如下:
Sub test()
Dim arr()
Dim dic As New Dictionary
arr = Range(“a2:b13”)
For i = LBound(arr) To UBound(arr)
dic(arr(i, 2)) = 1
Next
Sheet2.ListBox1.List = dic.Keys
End Sub
3.商品购物车小项目
项目描述:
商品目录如上图所示,用户点击商品,选择类别后,选择数量,然后显示价格
点击添加按钮,刚选择的商品被添加到下面的列表框里
这里用到了数组,字典,各种控件搭配使用
控件构成如下:
详细代码如下:
Dim arr()
Dim ID As String
Dim DJ As Long
Private Sub CommandButton1_Click()
If Me.ListBox1.Value <> “” And Me.ListBox2.Value <> “” And Me.ListBox3.Value <> “” And Me.TextBox1 > 0 Then
Me.ListBox4.AddItem
Me.ListBox4.List(Me.ListBox4.ListCount - 1, 0) = ID
Me.ListBox4.List(Me.ListBox4.ListCount - 1, 1) = Me.ListBox1.Value
Me.ListBox4.List(Me.ListBox4.ListCount - 1, 2) = Me.ListBox2.Value
Me.ListBox4.List(Me.ListBox4.ListCount - 1, 3) = Me.ListBox3.Value
Me.ListBox4.List(Me.ListBox4.ListCount - 1, 4) = Me.TextBox1.Value
Me.ListBox4.List(Me.ListBox4.ListCount - 1, 5) = Me.TextBox1.Value * Me.Label2.Caption
Else
MsgBox “请正确选择商品”
End If
End Sub
Private Sub ListBox1_Click()
Dim dic
Set dic = CreateObject(“Scripting.Dictionary”)
For i = LBound(arr) To UBound(arr)
If arr(i, 2) = Me.ListBox1.Value Then
dic(arr(i, 3)) = 1
End If
Next
Me.ListBox2.List = dic.keys
Me.ListBox3.Clear
Me.Label2.Caption = 0
End Sub
Private Sub ListBox2_Click()
Dim dic
Set dic = CreateObject(“Scripting.Dictionary”)
For i = LBound(arr) To UBound(arr)
If arr(i, 2) = Me.ListBox1.Value And arr(i, 3) = Me.ListBox2.Value Then
dic(arr(i, 4)) = 1
End If
Next
Me.ListBox3.List = dic.keys
End Sub
Private Sub ListBox3_Click()
For i = LBound(arr) To UBound(arr)
If arr(i, 2) = Me.ListBox1.Value And arr(i, 3) = Me.ListBox2.Value And arr(i, 4) = Me.ListBox3.Value Then
ID = arr(i, 1)
DJ = arr(i, 5)
End If
Next
Me.Label2.Caption = DJ
End Sub
Private Sub UserForm_Activate()
Dim dic
arr = Sheet1.Range(“a2:e13”)
Set dic = CreateObject(“Scripting.Dictionary”)
For i = LBound(arr) To UBound(arr)
dic(arr(i, 2)) = 1
Next
Me.ListBox1.List = dic.keys
End Sub
Private Sub UserForm_Click()
End Sub