数据类型
下表列举了常见的数据类型
Data type | Storage size | Range |
---|---|---|
Byte | 1 byte | 0 to 255 |
Boolean | 2 bytes | True or False |
Integer | 2 bytes | -32,768 to 32,767 |
Long (Long integer) | 4 bytes | -2,147,483,648 to 2,147,483,647 |
Date | 8 bytes | January 1, 100, to December 31, 9999 |
Object | 4 bytes | Any Object reference |
String (variable-length) | 10 bytes + string length | 0 to approximately 2 billion |
String (fixed-length) | Length of string | 1 to approximately 65,400 |
Variant (with numbers) | 16 bytes | Any numeric value up to the range of a Double |
Variant (with characters) | 22 bytes + string length (24 bytes on 64-bit systems) | Same range as for variable-length String |
Dictionary | Unknown | Unknown |
Collection | Unknown | Unknown |
数组操作
定义一个非动态数组
dim arr(5) as string '0-5
定义动态数组
dim arr() as string '不可声明数组大小
redim arr(5) '重新定义数组大小
arr(1) = 1
arr(2) = 2
redim arr(6) '原数据丢失
arr(1) = 1
arr(2) = 2
redim preserve arr(10) 'preserve关键字保存之前数组信息的同时伸缩数组
通过 i to j来定义数据
dim arr(1 to 10) as integer '数组从1到10
arr(1) = 1
debug.print arr(0) 'error
用从i到j下标的一个好处是,在Excel中单元格生成的variant数组,其开始下标从1开始
常用语数组相关的VBA自带函数
- Array 函数生成一个数组(见下)
- IsArray 判断是否是一个数组
- Ubound 函数显示数组最大下标
- Lbound 函数显示数组最小下标
- Join 函数,将数组按照规则合并(as String)
Array 函数
小标从0开始
生成二位数组 ?
$在定义中的作用
dim a$
其中$表示字符串相当于
dim a as String
另外,以此类推,有几个简写的符号
符号 | 代表的意思 | 示例 |
---|---|---|
% | 整数 | dim varInt% |
& | Long整数 | dim varLongInt& |
! | Single 单精度小数 | dim varSg! |
# | Double 单精度小数 | dim varDb# |
@ | Currency 货币型 | dim varCry# |
显示变量的类型 TypeName函数
Dim varStr$
varStr = "Hello World"
Debug.Print varStr
Debug.Print TypeName(varStr)
'显示的结果String
Dim varInt%
Dim varLong&
varInt = 23333
varLong = 233333333
Debug.Print varInt
Debug.Print TypeName(varInt)
'显示的结果Integer
Debug.Print varLong
Debug.Print TypeName(varLong)
'显示的结果Long
'varInt = varLong + varInt '溢出错误
varLong = varLong + varInt
Dim varCry@
varCry = 100
Debug.Print varCry
Debug.Print TypeName(varCry)
'显示的结果Currency
在Excel中打开Word与PowerPoint
Set wd = CreateObject("Word.Application")
wo.Documents.Open ThisWorkbook.Path & filename '打开文件'
Set ppt = CreateObject("Powerpoint.Application")
ppt.Presentations.Open ThisWorkbook.Path & filename '打开文件'