This is a tutorial about writing code in Excel spreadsheets using Visual Basic for Applications (VBA).
这是一个有关使用Visual Basic for Applications(VBA)在Excel电子表格中编写代码的教程。
Excel is one of Microsoft’s most popular products. In 2016, the CEO of Microsoft said "Think about a world without Excel. That's just impossible for me.” Well, maybe the world can’t think without Excel.
Excel是Microsoft最受欢迎的产品之一。 2016年,微软首席执行官说:“想想没有Excel的世界。对我而言,这简直是不可能的。” 好吧,也许没有Excel,世界将无法思考。
In 1996, there were over 30 million users of Microsoft Excel (source).
在1996年,有超过3000万的Microsoft Excel用户( 来源 )。
We’re one big happy family!
我们是一个幸福的大家庭!
In this tutorial, you’ll learn about VBA and how to write code in an Excel spreadsheet using Visual Basic.
在本教程中,您将了解VBA以及如何使用Visual Basic在Excel电子表格中编写代码。
You don’t need any prior programming experience to understand this tutorial. However, you will need:
您不需要任何编程经验即可了解本教程。 但是,您将需要:
Over the course of this article, you will learn:
在本文中,您将学到:
Here are some important concepts that you should be familiar with to fully understand this tutorial.
这里是一些重要概念,您应该熟悉这些概念才能完全理解本教程。
Objects: Excel is object-oriented, which means everything is an object - the Excel window, the workbook, a sheet, a chart, a cell. VBA allows users to manipulate and perform actions with objects in Excel.
对象 :Excel是面向对象的,这意味着一切都是对象-Excel窗口,工作簿,工作表,图表,单元格。 VBA允许用户对Excel中的对象进行操作和执行操作。
If you don’t have any experience with object-oriented programming and this is a brand new concept, take a second to let that sink in!
如果您没有任何面向对象编程的经验,而这是一个全新的概念,请花一点时间让它沉入其中!
Procedures: a procedure is a chunk of VBA code, written in the Visual Basic Editor, that accomplishes a task. Sometimes, this is also referred to as a macro (more on macros below). There are two types of procedures:
过程 :过程是用Visual Basic编辑器编写的,完成任务的VBA代码的一部分。 有时,这也称为宏(下面的更多宏)。 有两种类型的过程:
Functions: a group of VBA statements that performs one or more actions and returns one or more values
函数:一组执行一个或多个动作并返回一个或多个值的VBA语句
Note: you can have functions operating inside of subroutines. You’ll see later.
注意:可以在子例程内部运行函数。 待会见。
Macros: If you’ve spent any time learning more advanced Excel functionality, you’ve probably encountered the concept of a “macro.” Excel users can record macros, consisting of user commands/keystrokes/clicks, and play them back at lightning speed to accomplish repetitive tasks. Recorded macros generate VBA code, which you can then examine. It’s actually quite fun to record a simple macro and then look at the VBA code.
宏 :如果您花了很多时间学习更高级的Excel功能,则可能遇到了“宏”的概念。 Excel用户可以记录由用户命令/按键/单击组成的宏,并以闪电般的速度播放它们以完成重复的任务。 录制的宏会生成VBA代码,然后您可以对其进行检查。 录制一个简单的宏,然后查看VBA代码,实际上非常有趣。
Please keep in mind that sometimes it may be easier and faster to record a macro rather than hand-code a VBA procedure.
请记住,有时录制宏可能比手动编码VBA过程更容易,更快。
For example, maybe you work in project management. Once a week, you have to turn a raw exported report from your project management system into a beautifully formatted, clean report for leadership. You need to format the names of the over-budget projects in bold red text. You could record the formatting changes as a macro and run that whenever you need to make the change.
例如,也许您从事项目管理。 每周一次,您必须将来自项目管理系统的原始导出报告转换为格式精美,干净的报告,以进行领导。 您需要将预算外项目的名称设置为红色粗体。 您可以将格式更改记录为宏,并在需要进行更改时运行。
Visual Basic for Applications is a programming language developed by Microsoft. Each software program in the Microsoft Office suite is bundled with the VBA language at no extra cost. VBA allows Microsoft Office users to create small programs that operate within Microsoft Office software programs.
Visual Basic for Applications是Microsoft开发的一种编程语言。 Microsoft Office套件中的每个软件程序都与VBA语言捆绑在一起,无需额外费用。 VBA允许Microsoft Office用户创建在Microsoft Office软件程序中运行的小程序。
Think of VBA like a pizza oven within a restaurant. Excel is the restaurant. The kitchen comes with standard commercial appliances, like large refrigerators, stoves, and regular ole’ ovens - those are all of Excel’s standard features.
可以将VBA视为餐厅中的披萨烤箱。 Excel是餐厅。 厨房配有标准的商用设备,例如大型冰箱,火炉和普通的烤箱-这些都是Excel的标准功能。
But what if you want to make wood-fired pizza? Can’t do that in a standard commercial baking oven. VBA is the pizza oven.
但是,如果您想做木柴比萨怎么办? 在标准的商用烤箱中无法做到这一点。 VBA是披萨烤箱。
Yum.
好吃
Because wood-fired pizza is the best!
因为木比萨饼是最好的!
But seriously.
不过实话说。
A lot of people spend a lot of time in Excel as a part of their jobs. Time in Excel moves differently, too. Depending on the circumstances, 10 minutes in Excel can feel like eternity if you’re not able to do what you need, or 10 hours can go by very quickly if everything is going great. Which is when you should ask yourself, why on earth am I spending 10 hours in Excel?
很多人在工作中花费大量时间在Excel中。 Excel中的时间也不同。 根据情况的不同,如果您无法完成所需的工作,则在Excel中10分钟可能感觉很长久,而如果一切顺利,则很快就会花费10个小时。 什么时候应该问自己, 我到底为什么要在Excel中花费10个小时?
Sometimes, those days are inevitable. But if you’re spending 8-10 hours everyday in Excel doing repetitive tasks, repeating a lot of the same processes, trying to clean up after other users of the file, or even updating other files after changes are made to the Excel file, a VBA procedure just might be the solution for you.
有时,那些日子是不可避免的。 但是,如果您每天在Excel中花费8-10个小时来执行重复的任务,重复很多相同的过程,尝试在文件的其他用户之后进行清理,甚至在对Excel文件进行更改后甚至更新其他文件, VBA程序可能只是您的解决方案。
You should consider using VBA if you need to:
如果需要,您应该考虑使用VBA:
To write VBA, you’ll need to add the Developer tab to the ribbon, so you’ll see the ribbon like this.
要编写VBA,您需要在功能区中添加“开发人员”选项卡,这样您将看到功能区。
To add the Developer tab to the ribbon:
要将“开发人员”选项卡添加到功能区:
After you show the tab, the Developer tab stays visible, unless you clear the check box or have to reinstall Excel. For more information, see Microsoft help documentation.
显示选项卡后,“开发人员”选项卡将保持可见状态,除非您清除复选框或必须重新安装Excel。 有关更多信息,请参见Microsoft帮助文档。
Navigate to the Developer Tab, and click the Visual Basic button. A new window will pop up - this is the Visual Basic Editor. For the purposes of this tutorial, you just need to be familiar with the Project Explorer pane and the Property Properties pane.
导航到“开发人员”选项卡,然后单击“ Visual Basic”按钮。 将会弹出一个新窗口-这是Visual Basic编辑器。 出于本教程的目的,您只需要熟悉Project Explorer窗格和Property Properties窗格。
First, let’s create a file for us to play around in.
首先,让我们创建一个文件供我们玩。
Let’s rock and roll with some easy examples to get you writing code in a spreadsheet using Visual Basic.
让我们摇摆一些简单的示例,让您使用Visual Basic在电子表格中编写代码。
In the VBA Editor, select Insert -> New Module
在VBA编辑器中,选择插入->新建模块
Write this code in the Module window (don’t paste!):
在“模块”窗口中编写以下代码(不要粘贴!):
Sub Auto_Open() MsgBox ("Welcome to the XYZ Workbook.") End Sub
Sub Auto_Open()MsgBox(“欢迎使用XYZ工作簿。”)End Sub
Save, close the workbook, and reopen the workbook. This dialog should display.
保存,关闭工作簿,然后重新打开工作簿。 该对话框应显示。
Ta da!
da!
Depending on your familiarity with programming, you may have some guesses. It’s not particularly complex, but there’s quite a lot going on:
根据您对编程的熟悉程度,您可能会有一些猜测。 它不是特别复杂,但是有很多事情要做:
Auto_Open: this is the specific subroutine. It automatically runs your code when the Excel file opens - this is the event that triggers the procedure. Auto_Open will only run when the workbook is opened manually; it will not run if the workbook is opened via code from another workbook (Workbook_Open will do that, learn more about the difference between the two).
Auto_Open:这是特定的子例程。 当Excel文件打开时,它将自动运行您的代码-这是触发过程的事件。 Auto_Open仅在手动打开工作簿时运行; 如果通过另一个工作簿中的代码打开工作簿,它将无法运行(Workbook_Open将这样做,请详细了解两者之间的区别 )。
By default, a subroutine’s access is public. This means any other module can use this subroutine. All examples in this tutorial will be public subroutines. If needed, you can declare subroutines as private. This may be needed in some situations. Learn more about subroutine access modifiers.
默认情况下,子例程的访问是公共的。 这意味着任何其他模块都可以使用此子例程。 本教程中的所有示例都是公共子例程。 如果需要,可以将子例程声明为私有。 在某些情况下可能需要这样做。 了解有关子例程访问修饰符的更多信息。
In short, this is a simple subroutine that contains a function.
简而言之,这是一个包含函数的简单子例程。
Maybe you have a very important file that is accessed infrequently (say, once a quarter), but automatically updated daily by another VBA procedure. When it is accessed, it’s by many people in multiple departments, all across the company.
也许您有一个非常重要的文件,该文件很少被访问(例如,每季度一次),但又由另一个VBA过程每天自动更新。 当它被访问时,整个公司中多个部门的许多人都可以访问它。
In the VBA Editor, select Insert -> New Module
在VBA编辑器中,选择插入->新建模块
Write this code in the Module window (don’t paste!):
在“模块”窗口中编写以下代码(不要粘贴!):
Sub UserReportQuery() Dim UserInput As Long Dim Answer As Integer UserInput = vbYesNo Answer = MsgBox("Process the XYZ Report?", UserInput) If Answer = vbYes Then ProcessReport End Sub
子UserReportQuery()将UserInput设为长暗响应作为整数UserInput = vbYesNo答案= MsgBox(“处理XYZ报告?”,UserInput)如果Answer = vbYes,则ProcessReport结束Sub
Sub ProcessReport() MsgBox ("Thanks for processing the XYZ Report.") End Sub
Sub ProcessReport()MsgBox(“感谢您处理XYZ报告。”)
Save and navigate back to the Developer tab of Excel and select the “Button” option. Click on a cell and assign the UserReportQuery macro to the button.
保存并导航回到Excel的“开发人员”选项卡,然后选择“按钮”选项。 单击一个单元格,然后将UserReportQuery宏分配给该按钮。
Now click the button. This message should display:
现在单击按钮。 此消息应显示:
Click “yes” or hit Enter.
单击“是”或按Enter。
Once again, tada!
再次,多田!
Please note that the secondary subroutine, ProcessReport, could be anything. I’ll demonstrate more possibilities in example #3. But first...
请注意,辅助子例程ProcessReport可以是任何东西 。 我将在示例3中演示更多可能性。 但首先...
This example builds on the previous example and has quite a few new elements. Let’s go over the new stuff:
这个例子建立在前面的例子的基础上,并具有许多新元素。 让我们来看看新的东西:
Dim Answer As Integer: declares another variable called “Answer,” with a data type of Integer. Learn more about data types here.
Dim Answer As Integer:声明另一个名为“ Answer”的变量,其数据类型为Integer。 在此处了解有关数据类型的更多信息。
UserInput = vbYesNo: assigns a value to the variable. In this case, vbYesNo, which displays Yes and No buttons. There are many button types, learn more here.
UserInput = vbYesNo:为变量分配一个值。 在这种情况下,vbYesNo将显示“是”和“否”按钮。 按钮类型很多 , 在此处了解更多信息 。
This could be used in many, many ways. The value and versatility of this functionality is more so defined by what the secondary subroutine does.
可以以多种方式使用它。 此功能的价值和多功能性由辅助子例程的作用来定义。
For example, maybe you have a file that is used to generate 3 different weekly reports. These reports are formatted in dramatically different ways.
例如,也许您有一个用于生成3个不同的每周报告的文件。 这些报告的格式截然不同。
For loops are very useful if you need to perform repetitive tasks on a specific range of values - arrays or cell ranges. In plain English, a loop says “for each x, do y.”
如果需要对特定值范围(数组或单元格范围)执行重复性任务,则for循环非常有用。 用简单的英语来说,一个循环说“对于每个x,做y”。
In the VBA Editor, select Insert -> New Module
在VBA编辑器中,选择插入->新建模块
Write this code in the Module window (don’t paste!):
在“模块”窗口中编写以下代码(不要粘贴!):
Sub LoopExample() Dim X As Integer For X = 1 To 100 Range("A" & X).Value = X Next X End Sub
Sub LoopExample()Dim X作为X的整数,范围为1到100(“ A”和X)。值= X下一个X结束Sub
Save and navigate back to the Developer tab of Excel and select the Macros button. Run the LoopExample macro.
保存并导航回到Excel的“开发人员”选项卡,然后选择“宏”按钮。 运行LoopExample宏。
This should happen:
这应该发生:
Etc, until the 100th row.
等等,直到第100行。
For X = 1 To 100: this is the start of the For loop. Simply put, it tells the loop to keep repeating until X = 100. X is the counter. The loop will keep executing until X = 100, execute one last time, and then stop.
对于X = 1到100:这是For循环的开始。 简而言之,它告诉循环继续重复直到X =100。X是counter 。 循环将一直执行直到X = 100,最后一次执行,然后停止。
The For-Next loop is one of the most powerful functionalities of VBA; there are numerous potential use cases. This is a more complex example that would require multiple layers of logic, but it communicates the world of possibilities in For-Next loops.
For-Next循环是VBA最强大的功能之一。 有许多潜在的用例。 这是一个更复杂的示例,需要多层逻辑,但它在For-Next循环中传达了各种可能性。
Maybe you have a list of all products sold at your bakery in Column A, the type of product in Column B (cakes, donuts, or muffins), the cost of ingredients in Column C, and the market average cost of each product type in another sheet.
也许您在面包店的A列中列出了所有在面包店出售的产品,在B列中的产品类型(蛋糕,甜甜圈或松饼),在C列中的原料成本以及在每种产品类型中的市场平均成本清单另一张纸。
You need to figure out what should be the retail price of each product. You’re thinking it should be the cost of ingredients plus 20%, but also 1.2% under market average if possible. A For-Next loop would allow you to do this type of calculation.
您需要弄清楚每种产品的零售价是多少。 您认为这应该是原料成本加上20%,但如果可能的话,还应该比市场平ASP格低1.2%。 For-Next循环将允许您执行这种类型的计算。
Now that we’ve talked about pizza and muffins and oh-yeah, how to write VBA code in Excel spreadsheets, let’s do a learning check. See if you can answer these questions.
既然我们已经讨论了比萨饼和松饼,是的,如何在Excel电子表格中编写VBA代码,让我们进行学习检查。 看看您是否可以回答这些问题。
If you have a fair idea of how to you could answer these questions, then this was successful.
如果您对如何回答这些问题有一个明确的想法,那么这是成功的。
Whether you’re an occasional user or a power user, I hope this tutorial provided useful information about what can be accomplished with just a bit of code in your Excel spreadsheets.
无论您是偶尔使用还是高级用户,我都希望本教程提供有用的信息,说明只需使用Excel电子表格中的少量代码即可完成的工作。
Happy coding!
编码愉快!
Get Started with VBA, Microsoft Documentation
Microsoft文档VBA入门
Learning VBA in Excel, Lynda
在Excel,Lynda中学习VBA
I'm Chloe Tucker, an artist and developer in Portland, Oregon. As a former educator, I'm continuously searching for the intersection of learning and teaching, or technology and art. Reach out to me on Twitter @_chloetucker and check out my website at chloe.dev.
我是俄勒冈州波特兰市的艺术家兼开发商Chloe Tucker。 作为前教育工作者,我一直在寻找学与教,技术与艺术的交集。 伸手到我的Twitter上@_chloetucker ,并在检查了我的网站chloe.dev 。
翻译自: https://www.freecodecamp.org/news/excel-vba-tutorial/