VBA基础操作。

VBA真的是工作中十分常用的了,次次实习次次用,以前都是自学+写好的码改改就好,这学期又从头学了一遍最基础的操作~

按照五个部分来简单介绍一下:

  • 1 introduction

  • 2 User-defined functions

  • 3 Contol-flow statements

  • 4 Arrays

  • 5 Objects

1 Introduction

小贴士:alt+F11快捷键打开VB界面,F5执行代码,一定要储存为.xlsm不然里面的宏会丢失。

基本操作:

VBA是在module里编程,sub作为里面的一个个更小的模块运行,每个sub互不影响。

1
2
3
Sub Name [(Arguments)(As type)]
[Statements]
End Sub

其中arguments和as type都可以没有定义

举例:输入名字并返回:

1
2
3
4
Sub Name()
Name=inputbox("Enter your name:")
Msgbox("My name is " & Name & ".")
End Sub

2 User-Defined Functions

  • Declaring constant

在模块的开始,我们申明变量之后,下面的sub都可以使用这些变量,如果没有申明的话,sub之间不同变量(如果有相同名称)不会有影响。

1
2
Const name[As Type] = value
PublicConst name[As Type] = value
  • Declare variable

一定要先declare variable后写,不然默认为variant(既可以是文本,也可以是数据),后面代码写好后会出现问题。

1
Dim variable_name as Type
  • Function

就像python一样,写好function后面可以在任意sub里面调用,方便快捷。

1
2
3
4
Function name([Arg 1 as Type 1, Arg 2 as Type 2...])[As Type]
[Statements]
name = expression
End Function

举个栗子:三个数的加和

1
2
3
Function Sum3Numbers(a as Double, b as Double, c as Double)
Sum3Numbers = a + b + c
End Function
VBA的内置函数

如果需要调用Excel内置的函数:

1
Application.WorksheetFunction.(function)

3 Control-Flow Statements

  • 常用operators

1)if

就是if, then, else, else if, end if叠加。

有三种用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Type 1: one line syntax
result = iif (statement, statement if true, statement if false)

Type 2: one line if
if (condition) Then (result = value if true) Else (result = value if false)

Type 3: if Syntax
If (condition) Then
[Statement]
Else if (condition2) Then
[Statement]
Else
[Statement]
End if
2)Select case

不想用 if 的时候可以用用这个

1
2
3
4
5
6
Select Case (test variable)
Case (expression)
[Statement]
Case Else (expression)
[else statement]
End Select
举个栗子:

3)Do...Loop

有两种写法:

4)For...Next Loop

4 Arrays

  • Declare an array

跟定义其他类型的变量一样,Dim Arr(3) as Double/ Variant...

Array默认由0开始,如果想从1开始,那么有两种做法:第一是在module的最开始写上:Option base 1;或者直接写Dim Arr(1 to 3)

  • Dynamic Array

如果开始定义一个array为arr(3),后面如果想增加他的长度可以用:Redim arr(5),此时需要注意如果直接Redim会使得前面的数据arr(3)都消失,此时我们加上Redim Preserve arr(5)就会保留arr(3)之前输入的内容。

  • Multidimensional array

具体用法:

如果我们要在VBA里面replicate这个表格

  • Size of the array

如果想要知道这个arr的upper bound和lower bound,我们可以用

1
2
UBound(Arr)
LBound(Arr)
## 5 Objects 快捷键F2打开object browser,就可以看到如何对workbook, worksheet, range和cells进行操作。

这个没什么好讲的,打开object browser就可以看怎么做了(其实是我懒了。。。)平时上班操作一般都用这一部分进行不同的操作,进行增加一个表,填入数据,等等的操作......一定要好好掌握鸭!

交流区

交流请移步至精算后花园论坛 https://actuaryunion.com