基本语法知识
- 代码基本组成
- 每个宏都以 Sub 开始,宏的名称和括号
Sub HighlightDuplicateColumns()
- 从单引号开始直到行末尾是注释内容(中英文都可以)
- 实现功能的语句
End Sub
是宏的结束语句
2.变量和运算符
数据类型 | 数据范围 | 存储大小 |
---|---|---|
Byte | 0~255 | 1 |
Boolean(布尔) | TRUE/FAULSE | 2 |
Integer(整型) | -32768~32767 | 2 |
Long | -2147483648~2147483647 | 4 |
Single | / | 4 |
Double | / | 8 |
Currency(货币) | / | 8 |
Decimal(小数) | / | 12 |
Date(日期时间) | / | 8 |
Object(对象) | / | 4 |
String(字符串) | / | 字符串长度 |
Variant(数字) | / | 12 |
Variant(文本) | / | 字符串长度 |
通常使用 Dim 语句来声明变量,
Dim rng As Range
为使变量可被所有的过程使用,要用Public 语句声明公共变量:
Public rng As Range
未指定数据类型,默认为 Variant类型。
range对象,可以表示选中连续的单元格、同时选中的分散的单元格,支持操作单元格的内容、字体、删除线、颜色等
Set rng = Sheet1.range("A1:B2")
常用函数 | 具体函数 |
---|---|
设置背景色 | rng.Interior.Color = vbBlue |
EntireColumn,整列;EntireRow,整行 | rng.EntireColumn.Deleterng.EntireRow.Delete |
Find:查找包含指定值的单元格: | Set cell = rng.Find(What:=5, LookIn:=xlValues, LookAt:=xlWhole) |
Font:设置字体 | With rng.Font .Name = “黑体” .Bold = True .Color = vbRed .Size = 16 .Underline = xlUnderlineStyleSingleEnd With |
3.if 语句
- if <条件> then <语句 1> [else <语句2>]
- if <条件> then
<语句组 1>
[else
<语句组 2>]
end if - if <条件 1> then
<语句组 1>
[elseif <条件 2> then
<语句组 2> …
else
<语句组 n>]
end if
- mid函数
Mid(strMyString, 1, 1)
返回 strMyString 字符串变量从第 1 个字符开始的一个字符
5.with函数,可以简练代码阅读
With [A1]
.RowHeight = 10
.ColumnWidth = 15
End With
6.快捷进入编译界面:Alt+F11
7.模块
Sub 子程序
Function 函数
Property 属性
8.Do…Loop函数
- Do[{While|Until}<条件>]
[<过程语句>]
[Exit Do]
[<过程语句>]
Loop - Do
[<过程语句>]
[Exit Do]
[<过程语句>]
Loop[{While|Until}<条件>]