SlideShare a Scribd company logo
Excel VBA 程序设计基础
Excel VBA Programming Basics
XJTLU Library Training Session, May 8th 7-9pm
Hang Dong | 董行
PhD student in CSSE
Acknowledgement to all resources used in this
presentation: they are for educational use only.
上课之前
Before the class
 Let me know about you
 Chinese or English?
 Prior knowledge in programming?
 Prior knowledge in Excel (functions, charts, pivotTables)?
 Prior knowledge in VB (Microsoft Visual Basics)?
 Prior knowledge in Excel VBA?
 Know nothing above? (小白?)
 It doesn’t matter~~~
VBA, Visual Basics for Applications
简而言之,VBA是微软创造的一种编程语言,方便用户来自动地控制Excel等工具。
In a nutshell, it is a program language developed by Microsoft for users to
customise and automate tools like Excel.
用Excel VBA语言写出来的指令或操作过程,称为宏,即巨大的、可重复的操作。
Commands or operations written by Excel VBA are called Macros, which mean
large and repeatable operations.
什么是 VBA 和 宏: What is VBA and
Macro
+ =
Robot icon in Wikimedia, CC BY-SA 3.0,
https://commons.wikimedia.org/wiki/Robot#/med
ia/File:Animation2.gif
Advantage & disadvantages for VBA
Advantages:
 省时省力处理数据 Saving time for your tasks
 VBA自带安装在Excel中 Not need to install
 你会在职场中更加顺利 You become popular around your office
 在办公领域(尤其是金融会计领域)非常流行 Popular in Finance, accounting…
Disadvantages:
 你需要学习,虽然不难 You need to learn about coding, fortunately not hard
 VBA跨版本的兼容性不强,在提升 Compatibility across versions is not strong
Excel VBA is
still prospering
 A survey in 2016 shows that
VBA is alive, well and
prospering.
 Acknowledgement to an image in
ANALYSTCAVE. VBA IS DEAD? WHAT’S
THE FUTURE OF VBA?. 2016.2.
http://analystcave.com/vba-dead-
whats-future-vba/
Excel VBA 适用于哪类问题?
What problems can Excel VBA solve?
任何对Excel自动化的任务 Tasks related to automating some parts of Excel
 需要大量重复工作的任务,不止于 Repeated tasks not limited to,
 批量文本的格式化处理 Text formatting
 批量单元格,表,工作簿的处理 Cell, sheet and workbook processing
 批量图表、报告的生成 Charts and Reports generation
 批量数据的导入、加工和导出 Data import, processing and export
 创建Add-in加载项和Ribbon选项卡 [本节课不涉及] Create custom add-ins and Ribbon Tabs. [not be
covered today]
 其实什么都可以做…比如小型的信息管理系统 或者 游戏 Actually much more than you can
imagine…such as small information management system or a game.
主要内容 Content
 如何编写 Excel VBA 代码? How to use Excel VBA to solve problems?
 Variables
 Objects (Cell, Range, Sheet), Properties and Actions
 Basic Syntax: Loop and Control
 Basic Applications: data aggregation, import/export data, data
formatting
 How/Where to learn more about Excel VBA?
 Recording Macro
 Looking for tutorials online and books
新技能·开:启用开发工具 Enable “Developer”
 File -> Options -> Customize Ribbon -> Tick Developer
 Enable all macros (not necessary)
VBE (Visual Basic Editor)
 Developer Ribbon -> Visual Basic
Common Shortcuts in VBE in Windows
 Open VBE in Excel:Alt+F11
 属性窗口 Properties:F4
 对象浏览器 Object Browser:F2,Shift+F2
 帮助文档 Help Document:F1
 逐行调试 Step Into Debugging:F8
 设置断点 Toggle Breakpoint:F9
第一个程序 The first program
 “Hello World”
 通过按钮1,在第一个工作表的单元格“A1”上显示”Hello World!”.
 Show “Hello World!” on cell A1 in the first Sheet through Button1.
 通过按钮2,在Excel中弹出”Hello World!”.
 Pop dialog box “Hello World!” through Button2.
 hello_world.xlsm
录制宏
The 1st programme: Recording Macro
 录制宏 Recording Macro
 测试宏 Testing Macro
 检查/学习宏 Examining the Macro / Learn from the Macro code
 修改宏 Modify the Macro
 保存宏 Saving the Macro
录制宏 Recording Macro
 Developer -> Record Macro -> Set shortcut -> OK
 Performing some operations
 Stop Recording
测试宏 Testing Macro
 打开新的工作表,运行刚刚录制的宏
Run the recorded Macro on a new worksheet
 Method 1: 用快捷键运行 Ctrl + h Using the Shortcut Ctrl + h
 Method 2: 创建新的按钮来运行这个宏 Insert a button on the sheet
to run the Macro
 Method 3: 直接在VBE中运行 Run it directly in VBE
检查/学习宏 Examining the Macro /
Learn from the Macro code
 打开VBE环境编辑器,查看生成的宏代码
Check Macro Code in VBE.
 天啦噜!右边这一串是什么意思呢?
Oh!!! What does these mean on the right?
绿色部分不执行哦,只是注释
The green part does not execute: It is notes.
修改宏 Modify the Macro
 我们来一起加几行代码
Let put some new lines of code
 Add “For i=1 To 10” under Sub XX()
 Add “Next i” just before End Sub
 Change Range(A1).Select to
Range(“A & i”).Select
 Run it!
 我们再来一起加几行代码
Let put some new lines of code
 Add “If i Mod 2 = 0” before With XX.XX
 Add “End If” just after End With
 Run it!
保存宏 Save the Macro
 Developer -> Insert -> Button (From Control)
 File -> Save As -> set format as .xlsm
知识点1:Excel VBA 中的过程
Basic 1: Sub in Excel VBA
 过程 即 执行任务的 一组语句。A Sub procedure is a group of VBA statements
that performs an action (or actions) with Excel.
 Sub sub_name([parameters])
 End Sub
 从其它过程中调用某过程 Executing the procedure from another procedure
 Call sub_name
知识点2: 对象、属性和方法
Basic 2: Objects, properties and actions
 对象.方法/属性 Object.Action/Property
 Range(“A1”).Select ‘选择单元格A1 Select the Cell A1.
 ActiveCell.FormulaR1C1 ‘返回或设置指定对象的公式 Returns or sets the formula for the object.
 With-End With 结构
 对象.对象 Object.Object
 Application.Selection ‘选中的对象 Returns the selected object in the active window for
an Application object.
 Selection.Interior ‘单元格的内部 Returns an Interior object that represents the interior of the
specified object
对象与属性 Object and properties
 Range对象的Value属性(单元格.内容)
类似有 Range(“A1”).Row(单元格.行数)
Range(“A1”).Column(单元格.列数)
Range(“A1:B10”).Count(单元格.数量) Acknowledgement to the image from: Excel Home
编著. 别怕,Excel VBA其实很简单. 人民邮电出版社.
2012
对象与方法 Object and actions
 Range对象的Select方法
类似还有 Range(”A1”).Clear
(单元格.清除内容和格式)
Range(“A1”).ClearContents
(单元格.清除内容但不清除格式)
[a1].copy destination:=[a2]
(单元格.复制 到:=单元格)
Acknowledgement to the image from: Excel Home
编著. 别怕,Excel VBA其实很简单. 人民邮电出版社.
2012
对象层次结构 Hierarchical Structure of Objects
Application
Workbooks WorkSheets
Charts
Windows
AddIns
ChartObjects
Range
PageStep
PivotTable
…………
………… …………
Excel库下的类 Application类的对象 Workbooks类的对象 WorkSheets的对象
获取单元格并赋值 Access and set value to a
Range/Cell on Excel VBA
 Application.Workbooks(“Book1”).WorkSheets(1).Range(
“A1”).Value=“I love VBA”
 ThisWorkbook.WorkSheets(1).Range(“A1”).Value=“I
love VBA”
 Range(“A1”)=“I love VBA”
 [A1]=“I love VBA”
基本的运算符
 ‘赋值 ‘give a value
 a = 3
 a = a+1
 Cells(1,2).Value = “Hello”
 Range(“A1”).Value = “Hello”
 ‘加减乘除和求余
 +,-,*,/,mod cells(1,1).Value = 17 mod 3
 And, Or, Not
 If a>3 Or b>3 then c=2
 If Not c=2 then c=3 ‘If c<>2 then c=3
 If Range(“A1”).Value <> “” AND Range(“B1”).Value <> “” then …
知识点3: 程序控制结构 之 判断与循环
Basic 3: Control Flow, Loop and Decision Structures
 控制结构 Decision Structure
 ' Multiple-line syntax:
 If condition [ Then ]
 [ statements ]
 [ ElseIf elseifcondition [ Then ]
 [ elseifstatements ] ]
 [ Else
 [ elsestatements ] ]
 End If
 Example: see “if_then_else_show discount.xlsm”
Image from https://docs.microsoft.com/en-
us/dotnet/articles/visual-basic/programming-
guide/language-features/control-flow/decision-
structures
 循环结构用于遍历和重复执行代码
Loop Structure for repetitions
 比如你可以在代码中遍历以下内容 You can do a loop in
对一个区域中的所有单元格 all cells in a range
对所有打开的工作簿 all open workbooks
对所有工作表 all worksheets in a workbook
对一个单元格中的所有字符 all characters in a cell
对一个文件夹中的所有文件 all files in a folder
 循环结构
 For … Next …
 For Each … in Next
 Do … Loop
Continued: Loop Structure
Image from https://docs.microsoft.com/en-
us/dotnet/articles/visual-basic/programming-
guide/language-features/control-flow/loop-
structures
Continued: Loop Structure
“For Next” 循环结构
 For counter [ As datatype ] = start To end [ Step step ]
 [ statements ]
 [ Continue For ]
 [ statements ]
 [ Exit For ]
 [ statements ]
 Next [ counter ]
Continued: Loop Structure
Nested “For Next” 嵌套循环结构
 Sub FillRange ()
 Dim Col As Integer
 Dim Row As Long
 For Col = 1 To 5 ‘ 外部的循环 The outer loop
 For Row = 1 To 12 ‘ 内部的循环 The inner loop
 Cells(Row, Col) = Rnd
 Next Row
 Next Col
 End Sub
 See example “fill in range.xls”
Continued: Loop Structure
“For Each … Next” 循环结构
 For Each element [ As datatype ] In group
 [ statements ]
 [ Continue For ]
 [ statements ]
 [ Exit For ]
 [ statements ]
 Next [ element ]
 See example “get worksheet names.xlsm”
‘write worksheet names into column A
Sub shtname()
Dim sht As Worksheet, i As Integer
i = 1
For Each sht In Worksheets
Range("A" & i).Value = sht.Name
i = i + 1
Next sht
End Sub
Continued: Loop Structure
“Do Loop” 循环结构
 Do { While | Until } condition
 [ statements ]
 [ Continue Do ]
 [ statements ]
 [ Exit Do ]
 [ statements ]
 Loop
 Do
 [ statements ]
 [ Continue Do ]
 [ statements ]
 [ Exit Do ]
 [ statements ]
 Loop { While | Until } condition
Continued: Nested Control Structures
嵌套控制结构
 循环之中的循环 Loop inside a loop
 循环之中的判断 Decision inside a loop
 For i= 1 to 10
 If i mod 2 = 0 then
 ‘i 是1到10之间的偶数 i is an even number between 1 to 10.
 End If
 Next I
 判断之中的循环 Loop inside a decision
知识点4: VBA中的数据类型和变量
Basic 4: data type and variables in VBA
 Variant (the default data type)
 Boolean
 Integer/Long
 Single/Double
 String
 Date
Sub 按钮1_Click()
‘About the data type Variant
MsgBox TypeName(MyVar)
MyVar = "123"
MsgBox TypeName(MyVar)
MsgBox MyVar + MyVar
'MsgBox TypeName(MyVar)
MyVar = MyVar / 2
'MsgBox TypeName(MyVar)
MyVar = "Answer: " & MyVar
'MsgBox TypeName(MyVar)
MsgBox MyVar
End Sub
Acknowledgement to
the image from:
Excel Home编著. 别
怕,Excel VBA其实很
简单. 人民邮电出版
社. 2012
声明变量
Declare variables
 Dim a [as Variant]
 Dim IsLeaf as Boolean
 Dim columnNum as Integer
 Dim rowNum as Long
 Dim Meet_Rate as Single
 Dim Index_Meet_Rate as Double
 Dim FileName as String
 Option Explicit ‘要求强制声明所有变量
Using Option Explicit forces you to declare all your variables.
知识点5: 字符串的操作与函数
String Manipulation
 字符串的连结 We use the & operator to concatenate (join) strings.
 Dim text1 As String, text2 As String
text1 = "Hi"
text2 = "Tim"
MsgBox text1 & " " & text2
 字符串的截取 Extraction of substrings from a string
 Dim text As String
text = “example text”
MsgBox Left(text, 4) ‘To extract the leftmost characters from a string, use Left.
 MsgBox Right("example text", 2) ‘To extract the rightmost characters from a string, use
Right. We can also directly insert text in a function.
 MsgBox Mid("example text", 9, 2) ‘To extract a substring, starting in the middle of a
string, use Mid.
Adapted from http://www.excel-
easy.com/vba/string-manipulation.html
Continued…
 获取字符串的长度 To get the length of a string, use Len.
 MsgBox Len("example text")
 找到某字符子串在字符串中的位置
To find the position of a substring in a string, use Instr.
 MsgBox Instr("example text", "am")
 字符串的分割 split a text string into an array, by making use of a delimiter
character.
 Dim WrdArray() As String
 WrdArray() = Split("How are you")
Adapted from http://www.excel-
easy.com/vba/string-manipulation.html and
http://www.exceltrick.com/formulas_macros
/vba-split-function/
练习1
Exercise (on your handout)
 Recording and modifying a Macro 录制宏并进行修改
 录制一个宏 Record a Macro; 运行宏 Test a Macro
 查看宏 Examine a Macro; 修改宏 Modify a Macro
 再运行宏 Run a Macro again; 保存宏 Save a Macro
 请发挥自己的想象力录制宏,并完成自己的程序 Use your imagination to create a
Macro and complete your programme.
 推荐录制:新建工作表并创建表头,复制数据,改变格式,打开文件,保存文件等
Recommendation for recording as a macro: create new worksheet and titles, copy data,
change format, open and saving files.
练习2
Exercise (on your handout)
 请根据学生 (一共500名) 的雅思成绩 以及 申报的专业 来判断他们是否需要读语言
班。Please decide whether the student (500 of them in total) should take a
language class, according to their IELTS scores and applied majors.
 规则: 不用读语言班的条件 Rule: Criteria for not required taking a language class
Listen Speak Reading Writing In Total
Criteria for "Language" >=7 >=7 >=7 >=7
>=28
(7 in ave.)
Criteria for "Math" >=5.5 >=5.5 >=5.5 >=5.5
>=22
(5.5 in ave.)
Criteria for "Computer_Science" >=6 >=6 >=6 >=6
>=24
(6 in ave.)
练习2 答案
Excel VBA programming basics
应用1:多工作簿的数据汇总
Aggregating data from multiple workbooks
 不同班级成绩表的数据汇总 Put all students’ data together from different class
 一共有约30个不同的工作簿 There are around 30 worksheets
 See folder “data aggregation from workbooks”
序号 姓名 性别 族别 出生年月 家庭住址 班级 备注
1 陈发新 男 汉族 19980726 细岩村翁旮组 七1
2 李文雄 男 汉族 19981003 老院村茶园组 七1
3 李涛 男 汉族 19990912 左八村四组 七1
Adapted from 《别怕,其实VBA很简单》
4.7.10 汇总同文件夹下多工作簿数据
Acknowledgement to the case
adapted from: Excel Home编著.
别怕,Excel VBA其实很简单. 人
民邮电出版社. 2012
应用2: 多工作表的数据汇总
Aggregating data from multiple worksheets
 汇总成绩单: 将不同工作表中的数据复制到第一个工作表
Put together the records: To copy all data from multiple worksheets to the
first worksheet.
Acknowledgement to the case
adapted from: Excel Home编著.
别怕,Excel VBA其实很简单. 人
民邮电出版社. 2012
应用3:导入文本文档数据
Import data in .txt format
 可以通过录制宏的方式完成
This can be done through recording a macro.
 See example “Import_txt_data.xlsm”
其它数据获取和处理的应用?
Other apps about data acquisition and processing?
 从网页中获取数据
Getting data from webpage
 从html文档中获取数据
Getting data from html document
 从Access数据库中获取数据
Getting data from Access
 对数据进行格式化的处理
Formatting data to your own needs
Recording Macro
Modify Macro
with loop
with decision
…
Test/Run Macro
Make your program
user-friendly
倒数第二件事情 一些tips
The second last thing: some tips
 Use immediate window and local window
 Use F8 to check each line of code
 Set check point using your mouse
 Using Option Explicit to force declaring all variables
Immediate View and Local View
 (1) VBA -> View -> Immediate Window; (2) VBA -> View -> Local Window
今天没有涉及到但重要的知识 Important
knowledge not discussed today
 窗体 Form
 图表对象 The Object “Chart”
 自定义函数 Write your own Functions
 自定义Ribbon选项卡 Write your own Ribbons (XML)
 VSTO (Visual Basics, C#, .Net Framework)
 Apps for Office 2013 and upwards (XML)
 Roadmap for Apps for Office, VSTO, and VBA
https://blogs.msdn.microsoft.com/officeapps/2013/06/18/roadmap-for-
apps-for-office-vsto-and-vba/
资源推荐 Resources
网站 websites
 Excel VBA documentation for Excel 2013 and above
https://msdn.microsoft.com/en-us/library/office/ee861528.aspx [in English]
 Excel Home 论坛中的VBA板块 http://club.excelhome.net/forum-2-1.html [推荐]
 Excel Home. Excel VBA 视频教程 http://www.excelhome.net/video/excel/vba/
 善用百度、Bing、Google… Make good use of search engines.
 Excel Easy. http://www.excel-easy.com/vba.html [in English]
 VBA Q & A on Stack Overflow http://stackoverflow.com/questions/tagged/vba
图书 Books
 Walkenbach, J. (2015). Excel VBA programming for dummies. Hoboken, NJ: For Dummies, A
Wiley Brand. http://10.7.1.204:81/info.php?resid=99493065 (For XJTLU Lib users only)
 Excel Home编著. 别怕,Excel VBA其实很简单. 人民邮电出版社. 2012
 Excel Home编著. 别怕,Excel VBA其实很简单(第二版). 北京大学出版社. 2016
Books available
@ XJTLU Lib
 Chinese/English Books
Books available
@ XJTLU Lib
 English Books
Thank you for your attention!
Hang Dong
hang.dong@xjtlu.edu.cn

More Related Content

What's hot (20)

E learning excel vba programming lesson 3
E learning excel vba programming lesson 3
Vijay Perepa
 
MACROS excel
MACROS excel
Zenobia Sukhia
 
Vba
Vba
Juhi Mahajan
 
A Quick Simple MS Excel Macro
A Quick Simple MS Excel Macro
Pranav Ghode
 
Formulas and functions - By Amresh Tiwari
Formulas and functions - By Amresh Tiwari
Amresh Tiwari
 
Getting started with Microsoft Excel Macros
Getting started with Microsoft Excel Macros
Nick Weisenberger
 
Excel-VBA
Excel-VBA
DHRUYEN HADIYA
 
Excel Macro Magic
Excel Macro Magic
Elaine Giles
 
Excel macro
Excel macro
kundanpgcil
 
An introduction to vba and macros
An introduction to vba and macros
Er. Nawaraj Bhandari
 
Visual basic
Visual basic
KavithaAlagumalai
 
Basic Ms excel
Basic Ms excel
maharzahid0
 
Microsoft Excel - Macros
Microsoft Excel - Macros
Eladio Jose Abquina
 
Introduction to Microsoft Excel basics | Excel Intro | Excel | Excel for star...
Introduction to Microsoft Excel basics | Excel Intro | Excel | Excel for star...
Corp-sKool
 
Visual basic 6.0
Visual basic 6.0
Aarti P
 
M.S EXCEL
M.S EXCEL
Alvin Maderista
 
Excel formula
Excel formula
SBS TRANSPOLE LOGISTICS PVT. LTD.
 
MS Excel Macros/ VBA Project report
MS Excel Macros/ VBA Project report
Prafull Dhamankar
 
Intermediate ms excel for business elective course for dlsu-d hs
Intermediate ms excel for business elective course for dlsu-d hs
MarkFreudBolima
 
JavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScript
Laurence Svekis ✔
 
E learning excel vba programming lesson 3
E learning excel vba programming lesson 3
Vijay Perepa
 
A Quick Simple MS Excel Macro
A Quick Simple MS Excel Macro
Pranav Ghode
 
Formulas and functions - By Amresh Tiwari
Formulas and functions - By Amresh Tiwari
Amresh Tiwari
 
Getting started with Microsoft Excel Macros
Getting started with Microsoft Excel Macros
Nick Weisenberger
 
Introduction to Microsoft Excel basics | Excel Intro | Excel | Excel for star...
Introduction to Microsoft Excel basics | Excel Intro | Excel | Excel for star...
Corp-sKool
 
Visual basic 6.0
Visual basic 6.0
Aarti P
 
MS Excel Macros/ VBA Project report
MS Excel Macros/ VBA Project report
Prafull Dhamankar
 
Intermediate ms excel for business elective course for dlsu-d hs
Intermediate ms excel for business elective course for dlsu-d hs
MarkFreudBolima
 
JavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScript
Laurence Svekis ✔
 

Similar to Excel VBA programming basics (20)

Automating SolidWorks with Excel
Automating SolidWorks with Excel
Razorleaf Corporation
 
Sww 2008 Automating Your Designs Excel, Vba And Beyond
Sww 2008 Automating Your Designs Excel, Vba And Beyond
Razorleaf Corporation
 
Spreadsheets: Functional Programming for the Masses
Spreadsheets: Functional Programming for the Masses
kfrdbs
 
Financial modeling sameh aljabli lecture 6
Financial modeling sameh aljabli lecture 6
Sameh Algabli
 
Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan
 
Object-Based Programming Part One
Object-Based Programming Part One
PingLun Liao
 
Java Script ppt
Java Script ppt
Priya Goyal
 
Vizwik Coding Manual
Vizwik Coding Manual
Vizwik
 
Presentation - Course about JavaFX
Presentation - Course about JavaFX
Tom Mix Petreca
 
introduction to java scriptsfor sym.pptx
introduction to java scriptsfor sym.pptx
gayatridwahane
 
Demystifying The Solid Works Api
Demystifying The Solid Works Api
Razorleaf Corporation
 
elm-d3 @ NYC D3.js Meetup (30 June, 2014)
elm-d3 @ NYC D3.js Meetup (30 June, 2014)
Spiros
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipse
anshunjain
 
AVB201.1 MS Access VBA Module 1
AVB201.1 MS Access VBA Module 1
guest38bf
 
Cis 247 all i labs
Cis 247 all i labs
ccis224477
 
Vba Integrating Python For Enhanced Automation A Comprehensive Guide To Advan...
Vba Integrating Python For Enhanced Automation A Comprehensive Guide To Advan...
hedulakhalof
 
Cis247 a ilab 3 overloaded methods and static methods variables
Cis247 a ilab 3 overloaded methods and static methods variables
ccis224477
 
C++ functions
C++ functions
Mayank Jain
 
Front End Development: The Important Parts
Front End Development: The Important Parts
Sergey Bolshchikov
 
Cis247 a ilab 2 of 7 employee class
Cis247 a ilab 2 of 7 employee class
ccis224477
 
Sww 2008 Automating Your Designs Excel, Vba And Beyond
Sww 2008 Automating Your Designs Excel, Vba And Beyond
Razorleaf Corporation
 
Spreadsheets: Functional Programming for the Masses
Spreadsheets: Functional Programming for the Masses
kfrdbs
 
Financial modeling sameh aljabli lecture 6
Financial modeling sameh aljabli lecture 6
Sameh Algabli
 
Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan
 
Object-Based Programming Part One
Object-Based Programming Part One
PingLun Liao
 
Vizwik Coding Manual
Vizwik Coding Manual
Vizwik
 
Presentation - Course about JavaFX
Presentation - Course about JavaFX
Tom Mix Petreca
 
introduction to java scriptsfor sym.pptx
introduction to java scriptsfor sym.pptx
gayatridwahane
 
elm-d3 @ NYC D3.js Meetup (30 June, 2014)
elm-d3 @ NYC D3.js Meetup (30 June, 2014)
Spiros
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipse
anshunjain
 
AVB201.1 MS Access VBA Module 1
AVB201.1 MS Access VBA Module 1
guest38bf
 
Cis 247 all i labs
Cis 247 all i labs
ccis224477
 
Vba Integrating Python For Enhanced Automation A Comprehensive Guide To Advan...
Vba Integrating Python For Enhanced Automation A Comprehensive Guide To Advan...
hedulakhalof
 
Cis247 a ilab 3 overloaded methods and static methods variables
Cis247 a ilab 3 overloaded methods and static methods variables
ccis224477
 
Front End Development: The Important Parts
Front End Development: The Important Parts
Sergey Bolshchikov
 
Cis247 a ilab 2 of 7 employee class
Cis247 a ilab 2 of 7 employee class
ccis224477
 
Ad

More from Hang Dong (9)

Learning Relations from Social Tagging Data
Learning Relations from Social Tagging Data
Hang Dong
 
Rules for inducing hierarchies from social tagging data
Rules for inducing hierarchies from social tagging data
Hang Dong
 
语义沙龙:如何自动建构社会标签中的语义关系
语义沙龙:如何自动建构社会标签中的语义关系
Hang Dong
 
Enrichment of Cross-Lingual Information on Chinese Genealogical Linked Data
Enrichment of Cross-Lingual Information on Chinese Genealogical Linked Data
Hang Dong
 
关联数据的消费与应用构建: 以上海图书馆家谱开放数据为例
关联数据的消费与应用构建: 以上海图书馆家谱开放数据为例
Hang Dong
 
Learning structured knowledge from social tagging data: a critical review of ...
Learning structured knowledge from social tagging data: a critical review of ...
Hang Dong
 
Modeling health related topics in an online forum designed for the deaf & har...
Modeling health related topics in an online forum designed for the deaf & har...
Hang Dong
 
Identifying Evaluation Standards for Online Information Literacy Tutorials (O...
Identifying Evaluation Standards for Online Information Literacy Tutorials (O...
Hang Dong
 
My hometown -- Wuhan
My hometown -- Wuhan
Hang Dong
 
Learning Relations from Social Tagging Data
Learning Relations from Social Tagging Data
Hang Dong
 
Rules for inducing hierarchies from social tagging data
Rules for inducing hierarchies from social tagging data
Hang Dong
 
语义沙龙:如何自动建构社会标签中的语义关系
语义沙龙:如何自动建构社会标签中的语义关系
Hang Dong
 
Enrichment of Cross-Lingual Information on Chinese Genealogical Linked Data
Enrichment of Cross-Lingual Information on Chinese Genealogical Linked Data
Hang Dong
 
关联数据的消费与应用构建: 以上海图书馆家谱开放数据为例
关联数据的消费与应用构建: 以上海图书馆家谱开放数据为例
Hang Dong
 
Learning structured knowledge from social tagging data: a critical review of ...
Learning structured knowledge from social tagging data: a critical review of ...
Hang Dong
 
Modeling health related topics in an online forum designed for the deaf & har...
Modeling health related topics in an online forum designed for the deaf & har...
Hang Dong
 
Identifying Evaluation Standards for Online Information Literacy Tutorials (O...
Identifying Evaluation Standards for Online Information Literacy Tutorials (O...
Hang Dong
 
My hometown -- Wuhan
My hometown -- Wuhan
Hang Dong
 
Ad

Recently uploaded (20)

Smart Financial Solutions: Money Lender Software, Daily Pigmy & Personal Loan...
Smart Financial Solutions: Money Lender Software, Daily Pigmy & Personal Loan...
Intelli grow
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
Looking for a BIRT Report Alternative Here’s Why Helical Insight Stands Out.pdf
Looking for a BIRT Report Alternative Here’s Why Helical Insight Stands Out.pdf
Varsha Nayak
 
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Puppy jhon
 
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Maxim Salnikov
 
Smadav Pro 2025 Rev 15.4 Crack Full Version With Registration Key
Smadav Pro 2025 Rev 15.4 Crack Full Version With Registration Key
joybepari360
 
Integrating Survey123 and R&H Data Using FME
Integrating Survey123 and R&H Data Using FME
Safe Software
 
Reimagining Software Development and DevOps with Agentic AI
Reimagining Software Development and DevOps with Agentic AI
Maxim Salnikov
 
Migrating to Azure Cosmos DB the Right Way
Migrating to Azure Cosmos DB the Right Way
Alexander (Alex) Komyagin
 
Microsoft Business-230T01A-ENU-PowerPoint_01.pptx
Microsoft Business-230T01A-ENU-PowerPoint_01.pptx
soulamaabdoulaye128
 
dp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdf
pravkumarbiz
 
Open Source Software Development Methods
Open Source Software Development Methods
VICTOR MAESTRE RAMIREZ
 
Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
Plooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your way
Plooma
 
How Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines Operations
Insurance Tech Services
 
Step by step guide to install Flutter and Dart
Step by step guide to install Flutter and Dart
S Pranav (Deepu)
 
Automated Migration of ESRI Geodatabases Using XML Control Files and FME
Automated Migration of ESRI Geodatabases Using XML Control Files and FME
Safe Software
 
MOVIE RECOMMENDATION SYSTEM, UDUMULA GOPI REDDY, Y24MC13085.pptx
MOVIE RECOMMENDATION SYSTEM, UDUMULA GOPI REDDY, Y24MC13085.pptx
Maharshi Mallela
 
What is data visualization and how data visualization tool can help.pdf
What is data visualization and how data visualization tool can help.pdf
Varsha Nayak
 
Smart Financial Solutions: Money Lender Software, Daily Pigmy & Personal Loan...
Smart Financial Solutions: Money Lender Software, Daily Pigmy & Personal Loan...
Intelli grow
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
Looking for a BIRT Report Alternative Here’s Why Helical Insight Stands Out.pdf
Looking for a BIRT Report Alternative Here’s Why Helical Insight Stands Out.pdf
Varsha Nayak
 
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Puppy jhon
 
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Maxim Salnikov
 
Smadav Pro 2025 Rev 15.4 Crack Full Version With Registration Key
Smadav Pro 2025 Rev 15.4 Crack Full Version With Registration Key
joybepari360
 
Integrating Survey123 and R&H Data Using FME
Integrating Survey123 and R&H Data Using FME
Safe Software
 
Reimagining Software Development and DevOps with Agentic AI
Reimagining Software Development and DevOps with Agentic AI
Maxim Salnikov
 
Microsoft Business-230T01A-ENU-PowerPoint_01.pptx
Microsoft Business-230T01A-ENU-PowerPoint_01.pptx
soulamaabdoulaye128
 
dp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdf
pravkumarbiz
 
Open Source Software Development Methods
Open Source Software Development Methods
VICTOR MAESTRE RAMIREZ
 
Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
Plooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your way
Plooma
 
How Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines Operations
Insurance Tech Services
 
Step by step guide to install Flutter and Dart
Step by step guide to install Flutter and Dart
S Pranav (Deepu)
 
Automated Migration of ESRI Geodatabases Using XML Control Files and FME
Automated Migration of ESRI Geodatabases Using XML Control Files and FME
Safe Software
 
MOVIE RECOMMENDATION SYSTEM, UDUMULA GOPI REDDY, Y24MC13085.pptx
MOVIE RECOMMENDATION SYSTEM, UDUMULA GOPI REDDY, Y24MC13085.pptx
Maharshi Mallela
 
What is data visualization and how data visualization tool can help.pdf
What is data visualization and how data visualization tool can help.pdf
Varsha Nayak
 

Excel VBA programming basics

  • 1. Excel VBA 程序设计基础 Excel VBA Programming Basics XJTLU Library Training Session, May 8th 7-9pm Hang Dong | 董行 PhD student in CSSE Acknowledgement to all resources used in this presentation: they are for educational use only.
  • 2. 上课之前 Before the class  Let me know about you  Chinese or English?  Prior knowledge in programming?  Prior knowledge in Excel (functions, charts, pivotTables)?  Prior knowledge in VB (Microsoft Visual Basics)?  Prior knowledge in Excel VBA?  Know nothing above? (小白?)  It doesn’t matter~~~
  • 3. VBA, Visual Basics for Applications 简而言之,VBA是微软创造的一种编程语言,方便用户来自动地控制Excel等工具。 In a nutshell, it is a program language developed by Microsoft for users to customise and automate tools like Excel. 用Excel VBA语言写出来的指令或操作过程,称为宏,即巨大的、可重复的操作。 Commands or operations written by Excel VBA are called Macros, which mean large and repeatable operations. 什么是 VBA 和 宏: What is VBA and Macro + = Robot icon in Wikimedia, CC BY-SA 3.0, https://commons.wikimedia.org/wiki/Robot#/med ia/File:Animation2.gif
  • 4. Advantage & disadvantages for VBA Advantages:  省时省力处理数据 Saving time for your tasks  VBA自带安装在Excel中 Not need to install  你会在职场中更加顺利 You become popular around your office  在办公领域(尤其是金融会计领域)非常流行 Popular in Finance, accounting… Disadvantages:  你需要学习,虽然不难 You need to learn about coding, fortunately not hard  VBA跨版本的兼容性不强,在提升 Compatibility across versions is not strong
  • 5. Excel VBA is still prospering  A survey in 2016 shows that VBA is alive, well and prospering.  Acknowledgement to an image in ANALYSTCAVE. VBA IS DEAD? WHAT’S THE FUTURE OF VBA?. 2016.2. http://analystcave.com/vba-dead- whats-future-vba/
  • 6. Excel VBA 适用于哪类问题? What problems can Excel VBA solve? 任何对Excel自动化的任务 Tasks related to automating some parts of Excel  需要大量重复工作的任务,不止于 Repeated tasks not limited to,  批量文本的格式化处理 Text formatting  批量单元格,表,工作簿的处理 Cell, sheet and workbook processing  批量图表、报告的生成 Charts and Reports generation  批量数据的导入、加工和导出 Data import, processing and export  创建Add-in加载项和Ribbon选项卡 [本节课不涉及] Create custom add-ins and Ribbon Tabs. [not be covered today]  其实什么都可以做…比如小型的信息管理系统 或者 游戏 Actually much more than you can imagine…such as small information management system or a game.
  • 7. 主要内容 Content  如何编写 Excel VBA 代码? How to use Excel VBA to solve problems?  Variables  Objects (Cell, Range, Sheet), Properties and Actions  Basic Syntax: Loop and Control  Basic Applications: data aggregation, import/export data, data formatting  How/Where to learn more about Excel VBA?  Recording Macro  Looking for tutorials online and books
  • 8. 新技能·开:启用开发工具 Enable “Developer”  File -> Options -> Customize Ribbon -> Tick Developer
  • 9.  Enable all macros (not necessary)
  • 10. VBE (Visual Basic Editor)  Developer Ribbon -> Visual Basic
  • 11. Common Shortcuts in VBE in Windows  Open VBE in Excel:Alt+F11  属性窗口 Properties:F4  对象浏览器 Object Browser:F2,Shift+F2  帮助文档 Help Document:F1  逐行调试 Step Into Debugging:F8  设置断点 Toggle Breakpoint:F9
  • 12. 第一个程序 The first program  “Hello World”  通过按钮1,在第一个工作表的单元格“A1”上显示”Hello World!”.  Show “Hello World!” on cell A1 in the first Sheet through Button1.  通过按钮2,在Excel中弹出”Hello World!”.  Pop dialog box “Hello World!” through Button2.  hello_world.xlsm
  • 13. 录制宏 The 1st programme: Recording Macro  录制宏 Recording Macro  测试宏 Testing Macro  检查/学习宏 Examining the Macro / Learn from the Macro code  修改宏 Modify the Macro  保存宏 Saving the Macro
  • 14. 录制宏 Recording Macro  Developer -> Record Macro -> Set shortcut -> OK  Performing some operations  Stop Recording
  • 15. 测试宏 Testing Macro  打开新的工作表,运行刚刚录制的宏 Run the recorded Macro on a new worksheet  Method 1: 用快捷键运行 Ctrl + h Using the Shortcut Ctrl + h  Method 2: 创建新的按钮来运行这个宏 Insert a button on the sheet to run the Macro  Method 3: 直接在VBE中运行 Run it directly in VBE
  • 16. 检查/学习宏 Examining the Macro / Learn from the Macro code  打开VBE环境编辑器,查看生成的宏代码 Check Macro Code in VBE.  天啦噜!右边这一串是什么意思呢? Oh!!! What does these mean on the right? 绿色部分不执行哦,只是注释 The green part does not execute: It is notes.
  • 17. 修改宏 Modify the Macro  我们来一起加几行代码 Let put some new lines of code  Add “For i=1 To 10” under Sub XX()  Add “Next i” just before End Sub  Change Range(A1).Select to Range(“A & i”).Select  Run it!
  • 18.  我们再来一起加几行代码 Let put some new lines of code  Add “If i Mod 2 = 0” before With XX.XX  Add “End If” just after End With  Run it!
  • 19. 保存宏 Save the Macro  Developer -> Insert -> Button (From Control)  File -> Save As -> set format as .xlsm
  • 20. 知识点1:Excel VBA 中的过程 Basic 1: Sub in Excel VBA  过程 即 执行任务的 一组语句。A Sub procedure is a group of VBA statements that performs an action (or actions) with Excel.  Sub sub_name([parameters])  End Sub  从其它过程中调用某过程 Executing the procedure from another procedure  Call sub_name
  • 21. 知识点2: 对象、属性和方法 Basic 2: Objects, properties and actions  对象.方法/属性 Object.Action/Property  Range(“A1”).Select ‘选择单元格A1 Select the Cell A1.  ActiveCell.FormulaR1C1 ‘返回或设置指定对象的公式 Returns or sets the formula for the object.  With-End With 结构  对象.对象 Object.Object  Application.Selection ‘选中的对象 Returns the selected object in the active window for an Application object.  Selection.Interior ‘单元格的内部 Returns an Interior object that represents the interior of the specified object
  • 22. 对象与属性 Object and properties  Range对象的Value属性(单元格.内容) 类似有 Range(“A1”).Row(单元格.行数) Range(“A1”).Column(单元格.列数) Range(“A1:B10”).Count(单元格.数量) Acknowledgement to the image from: Excel Home 编著. 别怕,Excel VBA其实很简单. 人民邮电出版社. 2012
  • 23. 对象与方法 Object and actions  Range对象的Select方法 类似还有 Range(”A1”).Clear (单元格.清除内容和格式) Range(“A1”).ClearContents (单元格.清除内容但不清除格式) [a1].copy destination:=[a2] (单元格.复制 到:=单元格) Acknowledgement to the image from: Excel Home 编著. 别怕,Excel VBA其实很简单. 人民邮电出版社. 2012
  • 24. 对象层次结构 Hierarchical Structure of Objects Application Workbooks WorkSheets Charts Windows AddIns ChartObjects Range PageStep PivotTable ………… ………… ………… Excel库下的类 Application类的对象 Workbooks类的对象 WorkSheets的对象
  • 25. 获取单元格并赋值 Access and set value to a Range/Cell on Excel VBA  Application.Workbooks(“Book1”).WorkSheets(1).Range( “A1”).Value=“I love VBA”  ThisWorkbook.WorkSheets(1).Range(“A1”).Value=“I love VBA”  Range(“A1”)=“I love VBA”  [A1]=“I love VBA”
  • 26. 基本的运算符  ‘赋值 ‘give a value  a = 3  a = a+1  Cells(1,2).Value = “Hello”  Range(“A1”).Value = “Hello”  ‘加减乘除和求余  +,-,*,/,mod cells(1,1).Value = 17 mod 3  And, Or, Not  If a>3 Or b>3 then c=2  If Not c=2 then c=3 ‘If c<>2 then c=3  If Range(“A1”).Value <> “” AND Range(“B1”).Value <> “” then …
  • 27. 知识点3: 程序控制结构 之 判断与循环 Basic 3: Control Flow, Loop and Decision Structures  控制结构 Decision Structure  ' Multiple-line syntax:  If condition [ Then ]  [ statements ]  [ ElseIf elseifcondition [ Then ]  [ elseifstatements ] ]  [ Else  [ elsestatements ] ]  End If  Example: see “if_then_else_show discount.xlsm” Image from https://docs.microsoft.com/en- us/dotnet/articles/visual-basic/programming- guide/language-features/control-flow/decision- structures
  • 28.  循环结构用于遍历和重复执行代码 Loop Structure for repetitions  比如你可以在代码中遍历以下内容 You can do a loop in 对一个区域中的所有单元格 all cells in a range 对所有打开的工作簿 all open workbooks 对所有工作表 all worksheets in a workbook 对一个单元格中的所有字符 all characters in a cell 对一个文件夹中的所有文件 all files in a folder  循环结构  For … Next …  For Each … in Next  Do … Loop Continued: Loop Structure Image from https://docs.microsoft.com/en- us/dotnet/articles/visual-basic/programming- guide/language-features/control-flow/loop- structures
  • 29. Continued: Loop Structure “For Next” 循环结构  For counter [ As datatype ] = start To end [ Step step ]  [ statements ]  [ Continue For ]  [ statements ]  [ Exit For ]  [ statements ]  Next [ counter ]
  • 30. Continued: Loop Structure Nested “For Next” 嵌套循环结构  Sub FillRange ()  Dim Col As Integer  Dim Row As Long  For Col = 1 To 5 ‘ 外部的循环 The outer loop  For Row = 1 To 12 ‘ 内部的循环 The inner loop  Cells(Row, Col) = Rnd  Next Row  Next Col  End Sub  See example “fill in range.xls”
  • 31. Continued: Loop Structure “For Each … Next” 循环结构  For Each element [ As datatype ] In group  [ statements ]  [ Continue For ]  [ statements ]  [ Exit For ]  [ statements ]  Next [ element ]  See example “get worksheet names.xlsm” ‘write worksheet names into column A Sub shtname() Dim sht As Worksheet, i As Integer i = 1 For Each sht In Worksheets Range("A" & i).Value = sht.Name i = i + 1 Next sht End Sub
  • 32. Continued: Loop Structure “Do Loop” 循环结构  Do { While | Until } condition  [ statements ]  [ Continue Do ]  [ statements ]  [ Exit Do ]  [ statements ]  Loop  Do  [ statements ]  [ Continue Do ]  [ statements ]  [ Exit Do ]  [ statements ]  Loop { While | Until } condition
  • 33. Continued: Nested Control Structures 嵌套控制结构  循环之中的循环 Loop inside a loop  循环之中的判断 Decision inside a loop  For i= 1 to 10  If i mod 2 = 0 then  ‘i 是1到10之间的偶数 i is an even number between 1 to 10.  End If  Next I  判断之中的循环 Loop inside a decision
  • 34. 知识点4: VBA中的数据类型和变量 Basic 4: data type and variables in VBA  Variant (the default data type)  Boolean  Integer/Long  Single/Double  String  Date Sub 按钮1_Click() ‘About the data type Variant MsgBox TypeName(MyVar) MyVar = "123" MsgBox TypeName(MyVar) MsgBox MyVar + MyVar 'MsgBox TypeName(MyVar) MyVar = MyVar / 2 'MsgBox TypeName(MyVar) MyVar = "Answer: " & MyVar 'MsgBox TypeName(MyVar) MsgBox MyVar End Sub
  • 35. Acknowledgement to the image from: Excel Home编著. 别 怕,Excel VBA其实很 简单. 人民邮电出版 社. 2012
  • 36. 声明变量 Declare variables  Dim a [as Variant]  Dim IsLeaf as Boolean  Dim columnNum as Integer  Dim rowNum as Long  Dim Meet_Rate as Single  Dim Index_Meet_Rate as Double  Dim FileName as String  Option Explicit ‘要求强制声明所有变量 Using Option Explicit forces you to declare all your variables.
  • 37. 知识点5: 字符串的操作与函数 String Manipulation  字符串的连结 We use the & operator to concatenate (join) strings.  Dim text1 As String, text2 As String text1 = "Hi" text2 = "Tim" MsgBox text1 & " " & text2  字符串的截取 Extraction of substrings from a string  Dim text As String text = “example text” MsgBox Left(text, 4) ‘To extract the leftmost characters from a string, use Left.  MsgBox Right("example text", 2) ‘To extract the rightmost characters from a string, use Right. We can also directly insert text in a function.  MsgBox Mid("example text", 9, 2) ‘To extract a substring, starting in the middle of a string, use Mid. Adapted from http://www.excel- easy.com/vba/string-manipulation.html
  • 38. Continued…  获取字符串的长度 To get the length of a string, use Len.  MsgBox Len("example text")  找到某字符子串在字符串中的位置 To find the position of a substring in a string, use Instr.  MsgBox Instr("example text", "am")  字符串的分割 split a text string into an array, by making use of a delimiter character.  Dim WrdArray() As String  WrdArray() = Split("How are you") Adapted from http://www.excel- easy.com/vba/string-manipulation.html and http://www.exceltrick.com/formulas_macros /vba-split-function/
  • 39. 练习1 Exercise (on your handout)  Recording and modifying a Macro 录制宏并进行修改  录制一个宏 Record a Macro; 运行宏 Test a Macro  查看宏 Examine a Macro; 修改宏 Modify a Macro  再运行宏 Run a Macro again; 保存宏 Save a Macro  请发挥自己的想象力录制宏,并完成自己的程序 Use your imagination to create a Macro and complete your programme.  推荐录制:新建工作表并创建表头,复制数据,改变格式,打开文件,保存文件等 Recommendation for recording as a macro: create new worksheet and titles, copy data, change format, open and saving files.
  • 40. 练习2 Exercise (on your handout)  请根据学生 (一共500名) 的雅思成绩 以及 申报的专业 来判断他们是否需要读语言 班。Please decide whether the student (500 of them in total) should take a language class, according to their IELTS scores and applied majors.  规则: 不用读语言班的条件 Rule: Criteria for not required taking a language class Listen Speak Reading Writing In Total Criteria for "Language" >=7 >=7 >=7 >=7 >=28 (7 in ave.) Criteria for "Math" >=5.5 >=5.5 >=5.5 >=5.5 >=22 (5.5 in ave.) Criteria for "Computer_Science" >=6 >=6 >=6 >=6 >=24 (6 in ave.)
  • 43. 应用1:多工作簿的数据汇总 Aggregating data from multiple workbooks  不同班级成绩表的数据汇总 Put all students’ data together from different class  一共有约30个不同的工作簿 There are around 30 worksheets  See folder “data aggregation from workbooks” 序号 姓名 性别 族别 出生年月 家庭住址 班级 备注 1 陈发新 男 汉族 19980726 细岩村翁旮组 七1 2 李文雄 男 汉族 19981003 老院村茶园组 七1 3 李涛 男 汉族 19990912 左八村四组 七1 Adapted from 《别怕,其实VBA很简单》 4.7.10 汇总同文件夹下多工作簿数据 Acknowledgement to the case adapted from: Excel Home编著. 别怕,Excel VBA其实很简单. 人 民邮电出版社. 2012
  • 44. 应用2: 多工作表的数据汇总 Aggregating data from multiple worksheets  汇总成绩单: 将不同工作表中的数据复制到第一个工作表 Put together the records: To copy all data from multiple worksheets to the first worksheet. Acknowledgement to the case adapted from: Excel Home编著. 别怕,Excel VBA其实很简单. 人 民邮电出版社. 2012
  • 45. 应用3:导入文本文档数据 Import data in .txt format  可以通过录制宏的方式完成 This can be done through recording a macro.  See example “Import_txt_data.xlsm”
  • 46. 其它数据获取和处理的应用? Other apps about data acquisition and processing?  从网页中获取数据 Getting data from webpage  从html文档中获取数据 Getting data from html document  从Access数据库中获取数据 Getting data from Access  对数据进行格式化的处理 Formatting data to your own needs Recording Macro Modify Macro with loop with decision … Test/Run Macro Make your program user-friendly
  • 47. 倒数第二件事情 一些tips The second last thing: some tips  Use immediate window and local window  Use F8 to check each line of code  Set check point using your mouse  Using Option Explicit to force declaring all variables
  • 48. Immediate View and Local View  (1) VBA -> View -> Immediate Window; (2) VBA -> View -> Local Window
  • 49. 今天没有涉及到但重要的知识 Important knowledge not discussed today  窗体 Form  图表对象 The Object “Chart”  自定义函数 Write your own Functions  自定义Ribbon选项卡 Write your own Ribbons (XML)  VSTO (Visual Basics, C#, .Net Framework)  Apps for Office 2013 and upwards (XML)  Roadmap for Apps for Office, VSTO, and VBA https://blogs.msdn.microsoft.com/officeapps/2013/06/18/roadmap-for- apps-for-office-vsto-and-vba/
  • 50. 资源推荐 Resources 网站 websites  Excel VBA documentation for Excel 2013 and above https://msdn.microsoft.com/en-us/library/office/ee861528.aspx [in English]  Excel Home 论坛中的VBA板块 http://club.excelhome.net/forum-2-1.html [推荐]  Excel Home. Excel VBA 视频教程 http://www.excelhome.net/video/excel/vba/  善用百度、Bing、Google… Make good use of search engines.  Excel Easy. http://www.excel-easy.com/vba.html [in English]  VBA Q & A on Stack Overflow http://stackoverflow.com/questions/tagged/vba 图书 Books  Walkenbach, J. (2015). Excel VBA programming for dummies. Hoboken, NJ: For Dummies, A Wiley Brand. http://10.7.1.204:81/info.php?resid=99493065 (For XJTLU Lib users only)  Excel Home编著. 别怕,Excel VBA其实很简单. 人民邮电出版社. 2012  Excel Home编著. 别怕,Excel VBA其实很简单(第二版). 北京大学出版社. 2016
  • 51. Books available @ XJTLU Lib  Chinese/English Books
  • 52. Books available @ XJTLU Lib  English Books
  • 53. Thank you for your attention! Hang Dong [email protected]