VBA是Excel中使用的一种语言,对Excel的功能进行了增强。
定义一个简单的VBA过程示例如下:
Sub Fun()
MsgBox "Fun"
End Sub
我们可以在Excel通过录制宏,编辑VBA代码,然后查看宏,执行代码。
使用示例如下:
1.使用Worksheets、Range和Value设置某张工作表某个单元格的值
Sub SetName()
Worksheets("Sheet1").Range("A4").Value = "小明"
End Sub
2.使用Font.Size修改某张工作表某个单元格的字体大小
Sub SetFontSize()
Worksheets("Sheet1").Range("A4").Font.Size = 20
End Sub
3.通过End(xlDown)可往下移动到某列的最后一个单元格,使用Offset(row,column)可移动单元格位置
Sub AddNewRecord()
Range("A1").End(xlDown).Offset(1, 0).Select
Selection.Value = "小锋"
Selection.Offset(0, 1) = 100
End Sub
4.通过InputBox输入和MsgBox提示
Sub AddNewRecord()
Name = InputBox("请输入名字")
performance = InputBox("请输入绩效")
Range("D6").End(xlDown).Offset(1, 0).Select
Selection.Value = Name
Selection.Offset(0, 1).Value = performance
MsgBox ("输入成功")
End Sub
5.通过Debug.Print可在立即窗口打印调试信息,可使用循环进行操作
Sub AddNewRecord()
y = Range("D6").End(xlDown).Row
Debug.Print (y)
For x = 7 To y
Range("E" & x).Value = 500
Next
End Sub
6.可以通过Dim对变量进行声明,从而对输入内容进行校验
Sub AddNewRecord()
Dim Name As String, performance As Integer
Name = InputBox("请输入名字")
performance = InputBox("请输入绩效")
Range("D6").End(xlDown).Offset(1, 0).Select
Selection.Value = Name
Selection.Offset(0, 1).Value = performance
MsgBox ("输入成功")
End Sub
7.使用If-Then-Else-End If实现分支
Sub CalcPrize()
y = Range("D6").End(xlDown).Row
For x = 7 To y
If Range("E" & x).Value >= 2000 Then
Range("F" & x).Value = 10000
Else
Range("F" & x).Value = 0
End If
Next
End Sub