跳至主要內容

VBA

Caryam...大约 3 分钟

变量声明

Dim <Identifier> As <DataType>

Identifier是标识符,DataType是数据类型。
标识符就是变量的名称,必须以字母或下划线开头,只能使用字母、数字或下划线,同时不能与关键字(VBA中有特定意义的单词比如If)相同。

常用数据类型列表:

  1. Boolean
  2. Collection
  3. Date
  4. Double
  5. Integer
  6. Long
  7. Range
  8. Variant

详情请看data-type-summaryopen in new window
注意的是:这个是visual basic的数据类型,不包括excel中的数据类型。

数据类型

条件语句

If语句

一行If语句

If <condition> Then [statement]

多行If语句

If <condition> Then
    [statement1]
    [statement2]
    '......
End If

If-else语句

If <condition1> Then
    [statement1]
ElseIf <condition2> Then
    [statement2]
Else
    [statement3]
End If

Select Case语句

Select Case <value>
    Case Is <conditon1>:
        [statement1]
    Case Is <condition2>:
        [statement2]
    Case Else
        [statementElse]
End Select

condition不需要使用value,比如>=80就可以,不需要value >= 80

循环语句

For Each ... Next

For Each <element> in <group>
   [statement]
   [Exit For]
Next

For ... Next

For <counter> <start> To <end> [Step step]
    [statement]
    [Exit For]
Next <counter>

Do While/Until ... Loop

Do [{While|Until} conditon]
    [statement]
    [Exit Do]
Loop

使用While时,当condition为True时,循环执行;而使用Until时,则相反。
condition是可选的,当不存在时,程序陷入无限循环。

Do ... Loop While/Until

Do
    [statement]
    [Exit Do]
Loop [{While|Until} condition]

函数

声明

[Public | Private | Friend] [Static] Function <name>[(arglist)] [As <DataType>]
    [statement]
    [name = expression]
    [Exit Function]
    [Return expression]
End Function

'arglist is
[{ByVal|ByRef}] <arg1> As <DataType> [, {ByVal|ByRef}] <arg2> As <DataType>] [, ...]

使用Static修饰符时,函数内声明的局部变量在多次调用之间保留,不会重复创建和销毁。

调用

参考
stackoverflow questionopen in new window的第一个回答:解释三种调用方式的不同
Function Statementopen in new window:函数表达式官方文档
Value Types and Reference Typesopen in new window:值类型和引用类型

VBA存在三种调用方式,分别是:

FunctionName arg1, arg2, arg3, ...
FunctionName(arg1)
Call FunctionName(arg1, arg2, arg3, ...)

注意

  1. 第二种方式只能有一个实参,这是因为编译器将其圆括号里面的字符视为一个得到简单值的表达式,而arg1, arg2, arg3, ...显然是非法表达式;同时,这个实参会被视为ByValue
  2. 实参默认为ByRef,而不是ByVal。这在Function Statementopen in new window有说到,但是在另一篇文档open in new window又说到The default in Visual Basic is to pass arguments by value其实很迷惑,我想可能是因为文档过时的原因?

最佳实践

VBA的函数调用实在是过于复杂了,甚至让人十分疑惑。幸好的是使用Call可以规避这些问题。

最佳实践是这样的:

  1. 声明函数时明确指定需要ByVal还是ByRef
  2. 一律使用Call表达式调用函数

子过程

声明

[modifiers] Sub SubName[(parameterList)]
    [ statement ]
    [ Exit Sub ]
End Sub

parameterList和Function Statement的argList时一样的。

调用

SubName(param1, param2, ...)
上次编辑于:
贡献者: cary-mao
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.7