【VB题】使用自定义数据类型和动态数组实现:用户在文本框中输入,单击添加按钮,在右面的列表框中显示

2025-03-02 09:02:50
推荐回答(3个)
回答1:

Private Type UsrList ‘自定义数组(格式)
name As String
number As Integer
department As String
age As Integer
End Type
Dim Lst() as UsrLst '定义一个(数组)变量,代表自定义的Type格式

Private Sub Form_Load()
ReDim Lst(0) '这一组可以不用,也可以使用,关系到后续代码的数组Lbound运算
End Sub

Private Sub Command1_Click()
Dim n%, i%
i = UBound(Lst) + 1 '如果没有预置ReDim Lst(0) ,UBound(Lst)会提示出错
ReDim Preserve Lst(i)
Lst(i).number = int(Val(Text1.Text))
Lst(i).name = Cstr(Text2.Text)
Lst(i).department = Cstr(Text3.Text)
Lst(i).age = int(Val(Text4.Text))

List1.AddItem Lst(i).number & Space(6) & Lst(i).name & Space(6) & Lst(i).department & Space(7) & Lst(i).age

End Sub

回答2:

关键你把i%定义在Command1_Click() 过程内
因为i%是局部变量,你每次点Command1_Click时,i都是从0开始的。
所以 i%定义为全局变量或静态变量,让i能够保存上次的值,
这样达到保存前面的值了
第一种
Dim i%
Private Sub Command1_Click()
Dim n%
i = i + 1
Dim a() As List
ReDim Preserve a(1 To i)
a(i).number = Val(Text1.Text)
a(i).name = Text2.Text
a(i).department = Text3.Text
a(i).age = Val(Text4.Text)

第二种
Private Sub Command1_Click()
Dim n%
Static i%
i = i + 1
Dim a() As List
ReDim Preserve a(1 To i)
a(i).number = Val(Text1.Text)
a(i).name = Text2.Text
a(i).department = Text3.Text
a(i).age = Val(Text4.Text)

回答3:

建议你去学数据库,比这个方法要好。