12、使用InputBox函数进行输入
语法如下:
InputBox(prompt [,title] [,default] [,xpos] [,ypos] [,helpfile,context])
参数说明:
- prompt为提示内容,必选;
- title对话框标题;
- default为对话框中缺省的文字内容;
- xpos和ypos表示对话框距离屏幕左上角的距离,缺省则居中.
使用示例:
Private Sub b()
Dim a As String
a = InputBox("请输入姓名:", "输入对话框", "张三")
MsgBox (a)
End Sub
注:如果用户点击了“取消”按钮,则返回空串(“”).
13、循环及判断语句
使用exit for;exit loop;exit sub;exit function;exit select等退出对应的循环结构
【例一】 if then
Private Sub test()
If Sheet1.Cells(1, 1).Value = "1" Then
Application.Quit
End If
End Sub
【例二】if else then
Private Sub test()
Dim a As Integer
a = MsgBox("华工计算机", 1 + 64 + 0, "对话框")
If a = vbOK Then
MsgBox ("点击了确定")
Else
MsgBox ("点击了取消")
End If
Dim a%
score = 76
Debug.Print IIf(score > 60, IIf(score >= 70, IIf(score >= 80, IIf(score >= 90, "优秀", "良好"), "中等"), "及格"), "差")
End Sub
注:IIF跟公示编辑栏输入的IF语句一样可以直接嵌套
【例三】select case
Private Sub test()
Dim num As Integer
Dim res As String
res = InputBox("请输入分数")
If res <> "" Then '不是点击取消按钮
num = CInt(res) '强制转换为整型
Select Case (num)
Case 0 To 59
MsgBox ("不及格")
Case Is < 85
MsgBox ("良好")
Case Is < 98
MsgBox ("优秀")
Case 98, 99, 100
MsgBox ("特别优秀")
Case Else ‘没有匹配上面所有情况时候执行,可以省略
MsgBox ("输入分数不合法")
End Select
End If
End Sub
注意:select case中使用的is关键字与is比较运算符不同.
【例四】whle wend
Private Sub test()
Dim i, sum As Integer
sum = 0
i = 60
While i > 12
sum = sum + i
i = i - 1
Wend
MsgBox (sum)
End Sub
【例五】do loop
Private Sub test()
Dim i, sum As Integer
sum = 0
i = 60
Do While i >= 12
sum = sum + i
i = i - 1
Loop
MsgBox (sum)
Do
i = i + 2
Loop While i < 100
MsgBox (i)
Do Until i <= 0
i = i - 10
Loop
MsgBox (i)
i = 2
Do
i = i * 2
Loop Until i > 111
MsgBox (i)
End Sub
do loop的四种循环结构
do while … loop循环 |
先测试条件,如果成立则执行循环体 |
do … loop while循环 |
先执行一遍循环体,则测试循环条件,如果条件成立,则执行循环体 |
do until … while循环 |
先测试条件,如果不成立则执行循环体 |
do … loop until循环 |
先执行一遍循环体,则测试循环条件,如果条件不成立,则执行循环体 |
【例六】for next
Private Sub test()
Dim i, sum As Integer
sum = 0
For i = 1 To 12
sum = sum + i
Next
MsgBox (sum)
sum = 0
For i = 1 To 12 Step 2