当前位置:网站首页>Excel-vba quick start (I. macros, VBA, procedures, types and variables, functions)
Excel-vba quick start (I. macros, VBA, procedures, types and variables, functions)
2022-06-23 12:32:00 【Three uncle notes】
List of articles
One 、Excel VBA Introduce
VBA(Visual Basic for Applications), Is a way to extend Microsoft Office Functional programming language , Commonly used to extend Excel
function , by Excel Add automation scripts , And from improving Excel Office efficiency
1.1. macro
Macros are recording Excel The operation process , And then generate it automatically VBA Code tools , You can avoid writing a lot of VBA Code , It can be more simple
present Excel automation , But macros have limitations , When you want to implement functions with more complex logic , Still need to write VBA Code
1. Record macro
Microsoft Office Bring it with you VBA Related to the plug-in , But this article uses WPS Office, You need to install your own plug-ins to support VBA function ,
If you can't find the download address of the plug-in , You can leave a message
WPS Recording macros in is simple , Just follow the steps below :
- stay Excel Click on the development tool -> Record a new macro
- From this moment on , Yes Excel Will be recorded , Click end recording when you want to stop
Attach a WPS Complete action diagram of macro recorded in , The recorded content is , by C1 Add cells =SUM(A1,B1) expression :
2. other Excel Use recorded macros in the workbook
WPS Using macros in is just as simple , Just follow the steps below :
- Open... With macro Excel workbook
- Open the workbook where you want to use macros
- Click... In the workbook where you want to use the macro development tool -> VB macro -> Select the macro to use by name -> Can run
Attach a WPS The complete operation diagram of the macro used in , The contents of the macro are , by C1 Add cells =SUM(A1,B1) expression :

3. View the automatically generated... After recording a macro VBA Code
WPS View the corresponding... In the macro VBA Code , Just follow the steps below :
- Open... With macro Excel workbook
- Click... In the workbook where you want to use the macro development tool -> VB macro -> Select the macro to use by name -> edit
Attach a WPS View the macro automatically generated VBA Dynamic diagram of code :

Although the example is simple , But it can also show the basic functions of macros
1.2. Visual Basic Editor
Whether it's Microsoft Office still WPS Office,VBA The code is generic , Generally used to Visual Basic Editor to write VBA generation
code , stay WPS Open in Visual Basic The editor works as follows

Visual Basic Introduction to the basic layout of the editor
Because I didn't want to VBA Study too deeply , So for VB Editor interface , Simply understand the following important places
1. Where the code is written 
2. Common windows 
3. Other common windows 
Two 、VBA - Define the process
grammar
adopt Sub Keyword to define the process , Multiple processes can be defined in a module , Each process is actually a macro , Can be used alone ,
It can also be passed in one process Call The process of To call another procedure :
Sub Process name ()
' Process content
End Sub
demonstration
stay Excel Use in VBA There are generally two ways to code , One is triggered by events , One is triggered by a form control , Now through the form control
To demonstrate how to use VBA Code
1. The following processes are defined in the module :
Sub studyVBA()
Sheet1.Cells(1, 1) = " Start today VBA!!"
End Sub
2. stay Excel Add a button to the worksheet , And specify a macro for it ( We define the process name ):
3、 ... and 、VBA - Types and variables
1. data type
To define a variable, you must first know what type of variable you want to define ,VBA There are many data types in , Commonly used :
| Type the name | keyword | Keyword abbreviation |
|---|---|---|
| integer | Integer | % |
| Long integer | Long | & |
| Single precision | Single | ! |
| Double precision | Double | # |
| Character | String | $ |
It is not recommended to use abbreviations when declaring types ,VBA In addition to the basic types , Object types are also supported
2. Defining variables
stay VBA A common way to declare variables in is Public and Dim,Dim The declared variable is a local temporary variable , Its scope is its structure ,Public Declared variables are generally defined in the global , Not defined in a process
When learning related knowledge later , Can also learn Public Other USES , And other ways of defining variables
Declare variable syntax :
Dim Variable name As data type
Public Variable name As data type
Declare variables to demonstrate :
Public globalNum As Integer
Sub studyVBA()
Dim localNum As Integer
End Sub
Variable assignment :
Simply declaring variables is not enough , We also need to assign values to variables , There are two ways to assign values to variables :
- Assign values to variables of basic types , Use it directly
Variable name = valueThe grammar of - Assign values to variables of object type , Need to make use of
Setkeyword , The grammar isSet Variable name = value
Demonstration of variable assignment :
Sub studyVBA()
' Assign values to variables of basic types
Dim localNum As Integer
localNum = 100
' Assign values to object type variables
Dim obj As Range
Set obj = Range("a1")
End Sub
Four 、VBA - function
1. Ordinary function
Define the syntax for ordinary functions :
Function The name of the function ( Parameters 1, Parameters 2, Parameters n)
Logic code
The name of the function = Return value
End Function
Examples of defining common functions :
' Defined function
Function setValue(num1, num2)
setValue = num1 + num2
End Function
Examples of calling normal functions :
1. Use the defined function in the procedure
' Call a function in a procedure
Sub invoke()
Sheet1.Cells(1, 1) = setValue(1, 2)
End Sub
2. stay Excel The defined function is used as a function expression in 
2. Function with optional arguments
Function with optional arguments : When defining a function , Specify that the parameter is optional , This parameter can be passed when calling the function , Don't pass it on
Functions that define optional parameters - grammar :
Function The name of the function ( Parameters 1,Optional Parameters 2 as type , Parameters n)
Logic code
The name of the function = Return value
End Function
Functions that define optional parameters - Example :
' Defined function
Function setValue(num1, Optional num2 As Integer)
setValue = num1 + num2
End Function
Call a function with optional arguments - Example :
It is no different from calling ordinary functions , Only the parameters can be selected
' Call a function in a procedure , Choose not to pass in the second parameter
Sub invoke()
Sheet1.Cells(1, 1) = setValue(5)
End Sub
3. Functions with default values for arguments
Functions with default values for arguments : On the basis of functions with optional parameters , Set the default value for parameters without value transfer
Define functions with default values for parameters - grammar :
Function The name of the function ( Parameters 1,Optional Parameters 2 as type = The default value is , Parameters n)
Logic code
The name of the function = Return value
End Function
Define functions with default values for parameters - Example :
' Defined function
Function setValue(num1, Optional num2 As Integer = 100)
setValue = num1 + num2
End Function
Call a function with a default value for the parameter - Example :
' Call a function in a procedure , Choose not to pass in the second parameter
Sub invoke()
Sheet1.Cells(1, 1) = setValue(5)
End Sub
4. When calling a function, specify the parameter name to pass the value
When a function is called , If you do not want to pass in parameter values in the order of the parameter list , You can also use Function name ( Parameter name := Parameter values ) This kind of lattice for specifying parameter names
To make a function call
Example
Sub invoke()
Sheet1.Cells(1, 1) = setValue(num2:=100, num1:=200)
End Sub
5. Functions with variable length argument lists
When defining a function , The number of parameters cannot be determined , It needs to be decided by the caller when the function is called , In this scenario, functions with variable length parameter lists can be used
Functions with variable length argument lists - grammar
The function of variable length parameter list is to change the passed parameters into an array
Function Function name (ParamArray Parameter name ())
End Function
Example
Functions that define variable length parameter lists
' Defined function
Function setValue(ParamArray params())
For Each Item In params
Debug.Print Item
Next
End Function
Call the function of variable length parameter list
' Call function
Sub invoke()
' The parameter list does not need parentheses when the return value is not required
setValue 5, 6
' The parameter list must have parentheses when a return value is required
Dim returnVal As Integer
returnVal = setValue(5, 6)
End Sub
Function definition in either way , If you want to use the return value of the function when calling , The parameter list must be written in parentheses when calling , If not
Use the return value , Parentheses can be omitted from the call
边栏推荐
- Voice module: pyttsx sound change project
- Halcon knowledge: dyn_ Usage of threshold (scratch detection)
- 企业该如何进行高效IT运维管理?
- C#学习(高级课程)Day15——异常处理和命名空间
- The median annual salary exceeds 300000, and the salary of the first AI major graduate of Nanjing University is exposed
- QT知识:Qt Widgets小部件函数【02】
- Qt知识:视图框架QGraphicsWidget详解
- An idea of using keep alive to cache data in vue3 form pages
- Halcon知识:binocular_disparity 知识
- Qt 知识:使用 QGraphicsPixmapItem类
猜你喜欢

The list of open source summer winners has been publicized, and the field of basic software has become a hot application this year

go-zero微服务实战系列(六、缓存一致性保证)

Ros2 knowledge (1): start practicing robots

ROS2知识(2):网络设施

ROS察微【57】:配置手臂机器人来抓东西

Huawei cloud gaussdb heavily released HTAP for commercial use, defining a new paradigm of cloud native database 2.0

The computer broke down. I changed the computer. There was a problem installing the node environment. The URL is not defined

Proof and application of Chebyshev inequality

Slam Laser 2D (en utilisant Laser Scan matcher)

Qt 知识:使用 QGraphicsPixmapItem类
随机推荐
[no title] 2022 pressure pipeline patrol inspection and maintenance test questions and online simulation test
判断测试结束的标准有哪些?
ROS知识:librviz库的调用实践
面试题:举例说一下工作中你的接口测试是怎么做的?
冷板式、浸没式、喷淋式液冷散热能否引领高性能计算发展?
Proof and application of Chebyshev inequality
Huawei cloud gaussdb heavily released HTAP for commercial use, defining a new paradigm of cloud native database 2.0
Halcon原理:auto_threshold算子
Halcon principle: correlation matching
状态机框架
Halcon principle: Auto_ Threshold operator
ROS knowledge: point cloud files PCD format
Meta 称英国安全法将“扫描所有私人信息”,有侵犯用户隐私风险
CSS magic nugget mug; Optimization of CK, ES and redisearch schemes in ten million level data query; Why does module circular dependency not lead to dead loop Sauced afternoon tea issue 13
2022施工员-装饰方向-岗位技能(施工员)操作证考试题库模拟考试平台操作
C#学习(高级课程)Day13——反射
10-- 根据中序遍历和后序遍历,构造二叉树
Solution: argument type 'string' expected to be an instance of a class or class constrained type
Open classes are short videos! Tonight, I will teach you how to realize accurately!
2022工具钳工(初级)考试练习题模拟考试平台操作