[解析] 判断按键可以在窗体的KeyDown事件下用Chr函数将按键代码转换成字符与给定字符进行比较。使用 AddItem方法向列表框中添加列表项目,使用RemoveItem方法从列表框中删除列表项目。程序中用到了InputBox(),其格式为:
InputBox(prompt[,title][,default][,xpos][,ypos][,helpfile,context])
prompt:是一个字符串,其长度不得超过1024个字符,它是在对话框内显示的信息,用来提示用户输入。
title:字符串,它是对话框的标题,显示在对话框顶部的标题区。
default:字符串,用来显示输入缓冲区的默认信息。
xpos,ypos:是两个整数值,分别用来确定对话框与屏幕左边的距离(xpos)和上边的距离(ypos),它们的单位为twip。
helpfile,context:helpfile是一个字符串变量或字符串表达式,用来表示帮助文件的名字;context是一个数值变量或表达式,用来表示相关帮助主题的帮助目录号。解题步骤:
第一步:建立界面并设置控件属性。程序中用到的控件及其属性见表22-3。
表 22-3
控 件 |
属 性 |
设 置 值 |
Form1 |
KeyPreview |
Ttue |
Listbox |
Name |
List1 |
文本框 |
Name |
Text1 |
第二步:编写程序代码。
程序提供的代码:
Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
If Chr(KeyCode)="A" Then
Text1.Text=InputBox ("请输入要添加的项目")
' List1.AddItem ?
End If
If Chr(KeyCode)="D" Then
Text1.Text=InputBox ("请输入要删除的项目")
'For i=0 To ?
'If List1.List(i)=? Then
' List1.RemoveItem ?
End If
Next i
End If
End Sub
参考代码:
Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
If Chr(KeyCode)="A" Then
Text1.Text=InputBox ("请输入要添加的项目" )
List1. AddItem Text1
End If
If Chr(KeyCode)="D" Then
Text1.Text=InputBox ("请输入要删除的项目")
For i=0 To List1.ListCount-1
If List1.List(i)=Form1.Text1 Then
List1.RemoveItem (i)
End If
Next i
End If
End Sub
第三步:调试并运行程序。
第四步:按题目要求存盘。
(2) [解析] 文本框里的内容(包括数字)默认都是当作字符串来处理的,如果要参与数据运算则需先用Val函数将其转化为数字类型。这里需要指出的是利用Array函数对数组各元素赋值,声明的数组只能是Variant类型,数组的上下界可用 UBound和LBound函数获得,这两个函数的格式分别为:
LBound(数组[,维])
UBound(数组[,维])
这两个函数分别返回一个数组中的下界和上界。其中“数组”是一个数组名,“维”是要测试的维。LBound函数返回“数组”的下界,而UBound函数返回“数组”某一“维”的上界值,这两个函数一起使用即可确定一个数组的大小。解题步骤:
第一步:建立界面并设置控件属性。程序中用到的控件及其属性见表22-4。
表 22-4
控 件 |
属 性 |
设 置 值 |
命令按钮 |
Name Caption |
Command1 求平均值
|
文本框 |
Name |
Text1 |
文本框 |
Name |
Text2 |
文本框 |
Name |
Text3 |
文本框 |
Name |
Text4 |
第二步:编写程序代码。
程序提供的代码:
Option Base 1
Private Function Average(a() As Integer) As Sincle
Dim Start As Integer, Finish As Integer
Dim i As Integer
Dim Sum As Integer
'Start=?(a)
'Finish=?(a)
'Sum=?
For i=Start To Finish
'Sum=Sum+?
Next i
'Average=?
End Function
Private Sub Command1_Click()
Dim arr1
Dim arr2(4) As Integer
arr1=Array(Val(Text1.Text) , Val(Text2.Text) , Val(Text3.Text) , Val(Text4.Text) )
For i=1 To 4
arr2(i)=CInt(arr1(i) )
Next i
'Aver=Average(?)
Print "平均值是:"; Aver
End Sub
参考代码:
Option Base 1
Private Function Average(a() As Integer) As Single
Dim Start As Integer, Finish As Integer
Dim i As Integer
Dim Sum As Integer
Start=LBound(a)
Finish=UBound(a)
Sum= 0
For i=Start To Finish
Sum=Sum+a(i)
Next i
Average=Sum/Finish
End Function
Private Sub Command1_Click()
Dim arr1
Dim arr2(4) As Integer
arr1=Array(Val(Text1.Text) , Val(Text2.Text) , Val(Text3.Text) , Val(Text4.Text) )
For i=1 To 4
arr2(i)=CInt(arr1(i) )
Next i
Aver=Average (arr2)
Print "平均值是:"; Aver
End Sub
第三步:调试并运行程序。
第四步:按题目要求存盘