学习VBA-VBA基础语法讲解(一)
因为最近在做公司MRP(material Requirement Plan)的时候涉及到对许多excel报表的操作,因为报表来自不同国家和地区,格式是多种多样,如果是用C#来整理资料的话会出现效率低下,而且容易出错,所以最后想了一个办法用VBA把几百个excel的资料整理出来生成txt档案,然后再倒进系统,这样txt档案里的数据时标准统一的数据了,这样会减轻系统的负担,有错误也在进系统前档掉了,也减轻人工的操作(想想一天上传几百个excel也是挺繁琐的事情吧?)。那么下面让我来简单介绍下什么是VBA吧,应该有不少人不知道,我也是进公司后才知道的,开始不屑一顾,后来发现这个东西功能挺强大,在excel,word,ppt,outlook之间操作时游刃有余,而且能访问数据库、调用系统api、还能访问webservice,这样减轻我们的办公负担。
开篇介绍(因为一开始在公司做的ppt都是英文,有兴趣的可以看一下,因为这是个基础,后面各个章节会讲具体操作和按列)
1.
2.
In order to run VBA code your security settings must be properly set
Tools | Macro | Security…
1.
2.
At least Medium security must be set – each macro will require user verification to run
2.变量声明
Dim amount As Double
Dim year As Integer
Dim name As String Default (no type) is Variant Use Option Explicit in the declarations section to require declaration of variables
Public Const PI = 3.1, NumPLANETS = 9
Const PI2 = PI * 2
Const RELEASE = #1/1/99/#
To declare a variable that will refer to an instance of the Excel Worksheet clas
Dim ws1 As Worksheet
To put a reference into it
Set ws1 = Worksheets(“Sheet
对象集合
There is a special form of objects known as Collections
They contain references to other objects and collections
It is the mechanism by which the object hierarchy is defined
By convention, collection names are usually plural
Workbooks – list of Workbook objects
Worksheets – list of Worksheet objects
Range – list of objects that represent cells, columns, rows
The following example iterates through Workbooks collection
1 For Each ws In Worksheets
2
3 Debug.Print ws.Name
4
5 Next
6
7.逻辑
1.判断
If anyDate < Now Then anyDate = Now
If anyDate < Now Then
anyDate = Now
End If
If Index = 0 Then
CopyActiveControl
ClearActiveControl
Else If Index = 1 Then
CopyActiveControl
Else If Index = 2 Then
ClearActiveControl
Else
PasteActive Control
End If
2.选择
Select Case Index
Case 0
CopyActiveControl
ClearActiveControl
Case 1
CopyActiveControl
Case 2
ClearActiveControl
Case 3
PasteActive Control
Case Else
frmFind.Show
End Select
3.循环
Do While condition
statements
Loop
Do
statements
Loop While condition
Do Until condition
statements
Loop
Do
statements
Loop Until condition
For counter = start
Sub (routines)
no value returned
Called without parenthesis
mySub param1, param2
Called with parenthesis
Call mySub(param1, param2)
Functions
value returned
assign return value to function name
statements
Next counter