VBA知识学习
文章目录
- 打开开发工具
- 编写第一个VBA
- 使用VBA调试器
- VBA语法
打开开发工具
文件->选项->自定义功能区->开发工具
编写第一个VBA
点击开发工具 ->点击Visual Basic
选择sheet1->右键->插入->模块
Sub 第一个VBA程序()
MsgBox "Hello World!",vbOKonly, "VBA控制台程序" '输出程序信息
End Sub
点击调试->运行 进行测试
使用VBA调试器
调试过程后面为快捷键,按相应快捷键可以快速调试
Sub 第一个VBA程序() 'VBA程序以Sub开始,End Sub结束
Dim context As String 'Dim...As...声明变量
Dim title As String
Rem 将内容存入context变量
context = "欢迎进入Excel VAB世界!"
title = "Hello Excel VBA"
MsgBox context, vbOKOnly, title 'MsgBox为内置函数弹出框
End Sub
Sub 判断闰年()
Dim year As Integer
year = CInt(InputBox("请输入需要判断的年份:", "判断闰年"))
If year Mod 4 = 0 And year Mod 100 <> 0 Then
MsgBox "" & year & "是一个闰年", vbOKOnly, "判断闰年"
Else
If year Mod 100 = 0 And year Mod 400 = 0 Then
MsgBox "" & year & "是一个闰年", vbOKOnly, "判断闰年"
Else
MsgBox "" & year & "不是一个闰年", vbOKOnly, "判断闰年"
End If
End If
End Sub
Sub 求阶乘()
Dim i As Integer
Dim chengji As Long
chengji = 1
i = 1
While i <= 10
chengji = chengji * i
i = i + 1
Wend
MsgBox "10阶乘为:10! = " & chengji, vbOKOnly, "求阶乘"
End Sub
VBA语法
开始结束:Sub…End Sub
声明变量:Dim…As…
弹出框:MsgBox 内容 ,vbOKOnly,标题。拼接字符串 “” & year & “n内容”
输入框:InputBox(“提示语句:”)
转化为数字:CInt(内容)
条件语句:If…Else…End If
循环语句:While…Wend