One of the most outstanding qualities of Visual Basic is that it's a complete development environment. Whatever you want to do, there's a 'flavor' of Visual Basic to help you do the job! You can use Visual Basic for desktop and mobile and remote development (VB.NET), scripting (VBScript) and Office development (VBA !) If you have tried VBA and you want to know more about how to use it, this is the tutorial for you. (This course is based on the version of VBA found in Microsoft Office 2010.)
Visual Basic最杰出的品质之一就是它是一个完整的开发环境。 无论您想做什么,都有Visual Basic的“风味”可以帮助您完成工作! 您可以将Visual Basic用于桌面,移动和远程开发(VB.NET),脚本(VBScript)和Office开发( VBA !)。如果您尝试过VBA,并且想了解有关如何使用它的更多信息,请参阅本教程。为你 。 ( 本课程基于Microsoft Office 2010中提供的VBA版本。 )
If you're searching a course in Microsoft Visual Basic .NET, you have also found the right place. Check out: Visual Basic .NET 2010 Express - A "From the Ground Up" Tutorial
如果要在Microsoft Visual Basic .NET中搜索课程,则还找到了正确的位置。 检出:Visual Basic .NET 2010 Express-“从头开始”教程
VBA as a general concept will be covered in this article. There's more to VBA than you might think! You can also find articles about the Office VBA sisters:
VBA作为一般概念将在本文中介绍。 VBA有比您想象的更多的功能! 您还可以找到有关Office VBA姐妹的文章:
There are basically two way to develop programs that can work with Office applications: VBA and VSTO. In October 2003, Microsoft introduced an enhancement to the professional programming environment Visual Studio .NET called Visual Studio Tools for Office - VSTO. But even though VSTO leverages the considerable advantages of .NET in Office, VBA remains more popular than VSTO. VSTO requires the use of the Professional or higher version of Visual Studio - which will probably cost you more than the Office application you're using - in addition to the Office application. But since VBA is integrated with the host Office application, you don't need anything else.
开发可以与Office应用程序一起使用的程序的方法基本上有两种:VBA和VSTO。 2003年10月,Microsoft对专业编程环境Visual Studio .NET进行了增强,称为Visual Studio Tools for Office-VSTO。 但是,尽管VSTO充分利用了.NET在Office中的巨大优势,但VBA仍比VSTO更为流行。 VSTO除了使用Office应用程序外,还要求使用Visual Studio的专业版或更高版本-与您使用的Office应用程序相比,这可能会使您花费更多。 但是,由于VBA与宿主Office应用程序集成在一起,因此您不需要任何其他功能。
VBA is used primarily by Office experts who want to make their work faster and easier. You seldom see large systems written in VBA. VSTO, on the other hand, is used by professional programmers in larger organizations to create Add-Ins that can be quite sophisticated. An application from a third party, like a paper company for Word or an accounting firm for Excel, is more likely to be written using VSTO.
VBA主要由希望使其工作更快,更轻松的Office专家使用。 您很少看到用VBA编写的大型系统。 另一方面,大型组织中的专业程序员使用VSTO来创建非常复杂的加载项。 来自第三方的应用程序(例如Word的纸品公司或Excel的会计公司)更可能使用VSTO编写。
In their documentation, Microsoft notes that there are basically three reasons to use VBA:
Microsoft在其文档中指出,使用VBA基本上有三个原因:
-> Automation & Repetition - Computers can do the same thing over and over much better and faster than people can.
->自动化和重复-计算机可以一次又一次地比人们更好,更快地完成相同的事情。
-> Extensions to User Interaction - Do you want to suggest exactly how someone should format a document or save a file? VBA can do that. Do you want to validate what someone enters? VBA can do that too.
->用户交互的扩展-您是否确切建议某人应如何格式化文档或保存文件? VBA可以做到这一点。 您要验证某人输入的内容吗? VBA也可以做到这一点。
-> Interaction between Office 2010 Applications - A later article in this series is called Word and Excel Working Together. But if this is what you need, you might want to consider Office automation, that is, writing the system using VB.NET and then using the functions from an Office application like Word or Excel as needed.
-> Office 2010应用程序之间的交互-本系列中的后续文章称为Word and Excel Working Together。 但是,如果这是您需要的,则可能需要考虑Office自动化 ,即使用VB.NET编写系统,然后根据需要使用Office应用程序(如Word或Excel)中的功能。
Microsoft has stated that they will continue to support VBA and it's featured prominently in the Official Microsoft Office 2010 Development Roadmap. So you have as much assurance as Microsoft ever provides that your investment in VBA development won't be obsolete in the near future.
Microsoft已声明他们将继续支持VBA,并且在Microsoft Office 2010 正式开发路线图中突出显示了该功能。 因此,您可以像微软提供的那样,保证在不久的将来您对VBA开发的投资不会过时。
On the other hand, VBA is the last remaining Microsoft product that depends on VB6 "COM" technology. It's over twenty years old now! In human years, that would make it older than Lestat the Vampire. You might see that as "tried, tested and true" or you might think of it as "ancient, worn-out, and obsolete". I tend to favor the first description but you should be aware of the facts.
另一方面,VBA是最后一个依赖VB6“ COM”技术的Microsoft产品。 现在已经二十多岁了! 在人类时代,这将使其比吸血鬼莱斯特(Lestat)更古老。 您可能会认为这是“尝试,检验和真实的”,或者您可能会认为它是“古老,破旧且过时的”。 我倾向于第一个描述,但您应该了解事实。
The first thing to understand is the relationship between VBA and Office applications like Word and Excel. The Office application is a host for VBA. A VBA program can never be executed by itself. VBA is developed in the host environment (using the Developer tab in the Office application ribbon) and it must be executed as part of a Word document, an Excel workbook, an Access database or some other Office host.
首先要了解的是VBA与Office应用程序(如Word和Excel)之间的关系。 Office应用程序是VBA的主机 。 VBA程序永远不能单独执行。 VBA是在主机环境中开发的 (使用Office应用程序功能区中的“ 开发工具”选项卡),并且必须作为Word文档,Excel工作簿,Access数据库或某些其他Office主机的一部分执行。
The way VBA is actually used is different too. In an application like Word, VBA is used primarily as a way to access the objects of the host environment such as accessing the paragraphs in a document with the Word's Word.Document.Paragraphs object. Each host environment contributes unique objects that are not available in the other host environments. (For example, there is no "workbook" in a Word document. A workbook is unique to Excel.) The Visual Basic code is mainly there to make it possible to use objects customized for each Office host application.
VBA的实际使用方式也不同。 在Word之类的应用程序中,VBA主要用作访问主机环境对象的方式,例如使用Word的Word.Document.Paragraphs对象访问文档中的段落。 每个主机环境都提供其他主机环境中不可用的唯一对象。 (例如,在Word文档中没有“工作簿”。工作簿是Excel特有的。)Visual Basic代码主要是在其中,可以使用为每个Office宿主应用程序自定义的对象。
The fusion between VBA and host specific code can be seen in this code sample (taken from the Microsoft Northwind sample database) where purely VBA code is shown in red and Access specific code is shown in blue. The red code would be the same in Excel or Word but the blue code is unique to this Access application.
在此代码示例(摘自Microsoft Northwind示例数据库)中可以看到VBA与主机特定代码之间的融合,其中纯VBA代码以红色显示,而Access特定代码以蓝色显示。 红色代码在Excel或Word中将是相同的,但是蓝色代码对于此Access应用程序是唯一的。
VBA itself is almost the same as it has been for years. The way it integrates with the host Office application and the Help system has been improved more.
VBA本身与多年来已经几乎相同。 它与宿主Office应用程序和“帮助”系统集成的方式已得到进一步改进。
The 2010 version of Office doesn't display the Developer tab by default. The Developer tab takes you into the part of the application where you can create VBA programs so the first thing you need to do is change that option. Simply go to the File tab, Options, Customize Ribbon and click the Developer box in Main Tabs.
默认情况下,Office 2010版本不会显示“开发人员”选项卡。 “开发人员”选项卡将您带到可以创建VBA程序的应用程序部分,因此您需要做的第一件事就是更改该选项。 只需转到“文件”选项卡,“选项”,“自定义功能区”,然后单击“主选项卡”中的“开发人员”框。
The Help system works much more smoothly than it has in previous versions. You can get help for your VBA questions either offline, from a system that is installed with your Office application, or online from Microsoft over the Internet. The two interfaces are designed to look a lot alike:
“帮助”系统的工作比以前的版本更加顺畅。 您可以脱机,从Office应用程序安装的系统中获得有关VBA问题的帮助,也可以从Microsoft通过Internet在线获得有关VBA问题的帮助。 这两个接口的外观非常相似:
--------Click Here to display the illustration--------
--------点击此处显示插图--------
If your Internet connection is fast, the online help will give you more and better information. But the locally installed version will probably be faster and in most cases it's just as good. You might want to make the local help the default and then use the online help if the local version doesn't give you what you want. The fastest way to go online is to simply select "All Word" (or "All Excel" or other app) from the Search dropdown in the help. This will immediately go online and perform the same search, but it won't reset your default selection.
如果您的Internet连接速度很快,则在线帮助将为您提供更多更好的信息。 但是本地安装的版本可能会更快,并且在大多数情况下也是如此。 您可能希望将本地帮助设置为默认值,然后在本地版本无法满足您的需求时使用在线帮助。 最快的联机方法是简单地从帮助中的“搜索”下拉列表中选择“所有Word”(或“所有Excel”或其他应用程序)。 这将立即联机并执行相同的搜索,但不会重置您的默认选择。
--------Click Here to display the illustration--------
--------点击此处显示插图--------
On the next page, we get started with how to actually create a VBA program.
在下一页,我们开始如何实际创建VBA程序。
When VBA is "hosted" by an application like Word or Excel, the program "lives" in the document file that's used by the host. For example, in Word you can save your 'Word macro' (it's not a 'macro', but we won't quibble about terminology right now) either in a Word document or a Word template.
当VBA由Word或Excel之类的应用程序“托管”时,该程序“存在”于主机使用的文档文件中。 例如,在Word中,您可以在Word文档或Word模板中保存“ Word宏”(它不是 “宏”,但我们现在不会对术语进行质疑)。
Now suppose this VBA program is created in Word (this simple program just changes the font to bold for a selected line) and is saved in a Word document:
现在,假定此VBA程序是在Word中创建的(此简单程序只是将所选行的字体更改为粗体)并保存在Word文档中:
Sub AboutMacro()
'
' AboutMacro Macro
' Macro recorded 9/9/9999 by Dan Mabbutt
'
Selection.HomeKey Unit:=wdStory
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Selection.Font.Bold = wdToggle
Selection.EndKey Unit:=wdStory
End Sub
In earlier versions of Office, you could clearly see the VBA code stored as part of the document file in the saved Word document by viewing it in Notepad where everything in the Word document can seen. This illustration was produced with a previous version of Word because Microsoft changed the document format in the current version and VBA program code doesn't show up clearly as plain text anymore. But the principal is the same. Similarly, if you create an Excel spreadsheet with an "Excel macro" it will be saved as part of an .xlsm file.
在早期版本的Office中,您可以通过在记事本中查看Word文档中所有内容的方式清楚地看到VBA代码作为文档文件的一部分存储在已保存的Word文档中。 该图是使用Word的早期版本制作的,因为Microsoft在当前版本中更改了文档格式,并且VBA程序代码不再清楚地显示为纯文本。 但是原理是一样的。 同样,如果使用“ Excel宏”创建Excel电子表格,则该电子表格将另存为.xlsm文件。
--------Click Here to display the illustration--------
--------点击此处显示插图--------
VBA and Security
VBA和安全性
One of the most effective computer virus tricks in the past was to insert malicious VBA code into an Office document. With previous versions of Office, when a document was opened, the virus could run automatically and create havoc on your machine. This open security hole in Office was starting to impact Office sales and that really got Microsoft's attention. With the current 2010 generation of Office, Microsoft has thoroughly plugged the hole. In addition to the improvements mentioned here, Microsoft has enhanced Office security in ways that you might not even notice right down to the hardware level. If you're hesitant to use VBA because you heard that it wasn't safe, be assured that Microsoft has gone the extra mile to change that now.
过去,最有效的计算机病毒技巧之一是将恶意VBA代码插入Office文档。 在早期版本的Office中,打开文档时,该病毒可能会自动运行并在您的计算机上造成严重破坏。 Office中的此开放安全漏洞已开始影响Office的销售,这确实引起了Microsoft的注意。 在当前的2010年Office版本中,Microsoft已彻底填补了漏洞。 除了此处提到的改进之外,Microsoft还以您甚至可能在硬件级别上都没有注意到的方式增强了Office安全性。 如果您因为听说VBA不安全而犹豫不决,请放心,Microsoft已经付出了更多的努力来改变这一现状。
The most important change was to create a special document type just for Office documents that include VBA programs. In Word, for example, MyWordDoc.docx cannot contain a VBA program because Word will not allow programs in a file saved with a "docx" file extension. The file must be saved as a "MyWordDoc.docm" for the VBA programming to be allowed as part of the file. In Excel, the file extension is ".xlsm".
最重要的更改是仅为包含VBA程序的Office文档创建一个特殊的文档类型。 例如,在Word中,MyWordDoc.docx不能包含VBA程序,因为Word不允许以“ docx”文件扩展名保存的文件中的程序。 该文件必须另存为“ MyWordDoc.docm”,以允许VBA编程作为文件的一部分。 在Excel中,文件扩展名是“ .xlsm”。
To go along with this enhanced document type, Microsoft created a new security subsystem in Office called the Trust Center. Essentially, you can customize how your Office application treats documents containing VBA code in fine detail. You open the Trust Center from the Developer tab in your Office application by clicking Macro Security in the Code section of the ribbon.
为了配合这种增强的文档类型,Microsoft在Office中创建了一个新的安全子系统,称为“信任中心”。 本质上,您可以自定义Office应用程序如何详细处理包含VBA代码的文档。 通过单击功能区“代码”部分中的“宏安全性”,从Office应用程序中“开发人员”选项卡中打开“信任中心”。
--------Click Here to display the illustration--------
--------点击此处显示插图--------
Some of the options are designed to "harden" your Office applications so malicious code doesn't run and others are designed to make it easier for developers and users to use VBA without having security unnecessarily slowing things down. As you can see, there are a lot of ways that you can customize security and going through all of them is far beyond the scope of this article. Fortunately, Microsoft's site has extensive documentation on this topic. And it's also fortunate that the default security settings are good for most requirements.
有些选项旨在“加固”您的Office应用程序,以使恶意代码不会运行,而其他选项则旨在使开发人员和用户更轻松地使用VBA,而不必担心不必要的安全性。 如您所见,您可以通过多种方式自定义安全性,而通过所有这些方式远远超出了本文的范围。 幸运的是,Microsoft网站上有大量有关此主题的文档。 而且幸运的是,默认的安全设置可以满足大多数要求。
Since VBA is tied to the host Office application, you have to run it there. That topic is covered starting on the next page.
由于VBA已绑定到宿主Office应用程序,因此您必须在其中运行它。 从下一页开始介绍该主题。
How Do I Run a VBA Application
如何运行VBA应用程序
That's actually a very good question because it's the first one that users of your application will ask. There are basically two ways:
这实际上是一个非常好的问题,因为这是您的应用程序用户会问的第一个问题。 基本上有两种方法:
-> If you decide not to use a control, like a Button, to start the program, then you must use the Macros command on the ribbon (Developer tab, Code group). Select the VBA program and click Run. But this might seem a little too much to some of your users. For example, you might not want the Developer tab to even be available to them. In that case ...
->如果决定不使用按钮之类的控件来启动程序,则必须使用功能区(“开发人员”选项卡,“代码”组)上的“宏”命令。 选择VBA程序,然后单击“运行”。 但这对于您的某些用户来说似乎有点过多。 例如,您可能甚至不希望“开发人员”选项卡对他们可用。 在这种情况下 ...
-> You need to add something that the user can click or type to start the application. In this article, we will look at the Button control. But it could be clicking a shortcut, an icon on a toolbar or even the act of entering data. These are called events and what we will write in this and later articles is event code - program code that is automatically run when some specific event - like clicking a Button control - happens.
->您需要添加一些用户可以单击或键入的内容以启动应用程序。 在本文中,我们将研究Button控件。 但是它可能是单击快捷方式,工具栏上的图标,甚至是输入数据的行为。 这些被称为事件 ,我们将在本文及其后的文章中介绍的是事件代码 -当某些特定事件(例如单击Button控件)发生时自动运行的程序代码。
UserForms, Form Controls and ActiveX Controls
用户窗体,窗体控件和ActiveX控件
If you're not just selecting a macro, the most common way to run a VBA program is to click a button. That button can either be a form control or an ActiveX control. To a degree, your choices depend on the Office application that you're using. Excel provides slightly different choices than Word, for example. But these fundamental types of controls are the same.
如果您不只是选择宏,则运行VBA程序的最常见方法是单击一个按钮。 该按钮可以是表单控件或ActiveX控件 。 在一定程度上,您的选择取决于您使用的Office应用程序。 例如,Excel提供的选择与Word略有不同。 但是控件的这些基本类型是相同的。
Because it offers the most flexibility, let's look at what you can do with Excel 2010. A simple text message will be inserted into a cell when several different buttons are clicked just to make the differences more clear.
因为它提供了最大的灵活性,所以让我们看一下您可以使用Excel 2010做些什么。单击几个不同的按钮只是为了使区别更加清楚,一条简单的文本消息将插入到单元格中。
To get started, create a new Excel workbook and select the Developer tab. (If you have another Office application, a variation of these instructions should work.)
首先,创建一个新的Excel工作簿并选择“开发人员”选项卡。 (如果您有另一个Office应用程序,则可以使用这些说明的变体。)
Click the Insert icon. We'll work with the Form Controls button first.
单击插入图标。 我们将首先使用“表单控件”按钮。
Form controls are the older technology. In Excel, they were first introduced in version 5.0 in 1993. We'll work with VBA UserForms next but form controls can't be used with them. They're also not compatible with the web. Form controls are placed directly on the worksheet surface. On the other hand, some ActiveX controls - which we consider next - can't be used directly on worksheets.
表单控件是较旧的技术。 在Excel中,它们是在1993年的5.0版中首次引入的。接下来,我们将使用VBA UserForms,但是不能将表单控件与它们一起使用。 它们也与网络不兼容。 表单控件直接放置在工作表表面上。 另一方面,某些ActiveX控件-我们接下来将要讨论的-不能直接在工作表上使用。
Form controls are used with a "click and draw" technique. Click the Button form control. The mouse pointer will change into a plus sign. Draw the control by dragging over the surface. When you release the mouse button, a dialog pops up asking for a macro command to connect with the button.
表单控件与“单击并绘制”技术一起使用。 单击按钮窗体控件。 鼠标指针将变为加号。 通过在表面上拖动来绘制控件。 释放鼠标按钮时,会弹出一个对话框,要求使用宏命令与该按钮连接。
--------Click Here to display the illustration--------
--------点击此处显示插图--------
Especially when you're creating a control for the first time, you won't have a VBA macro waiting to be connected with the button, so click New and the VBA Editor will open with the suggested name already filled into the shell of an event subroutine.
尤其是当您第一次创建控件时,不会有等待与按钮连接的VBA宏,因此单击“新建”,VBA编辑器将打开,其建议名称已经填充到事件的外壳中子程序。
--------Click Here to display the illustration--------
--------点击此处显示插图--------
To complete this very simple application, just type this VBA code statement inside the Sub:
要完成这个非常简单的应用程序,只需在Sub中键入以下VBA代码语句:
Cells(2, 2).Value = "Form Button Clicked"
An ActiveX button is almost exactly the same. One difference is that VBA places this code in the worksheet, not in a separate module. Here's the complete event code.
ActiveX按钮几乎完全相同。 一个区别是VBA将此代码放在工作表中,而不是在单独的模块中。 这是完整的事件代码。
Private Sub CommandButton1_Click()
Cells(4, 2).Value = "ActiveX Button Clicked"
End Sub
In addition to placing these controls directly on the worksheet, you can also add a UserForm to the project and place controls on that instead. UserForms - about the same thing as Windows forms - have a lot of advantages in being able to manage your controls more like a normal Visual Basic application. Add a UserForm to the project in the Visual Basic editor. Use the View menu or right-click in Project Explorer.
除了将这些控件直接放置在工作表上之外,您还可以将UserForm添加到项目中并将控件放置在该项目上。 UserForms(与Windows窗体几乎相同)在能够像常规Visual Basic应用程序一样管理控件方面具有很多优势。 将用户窗体添加到Visual Basic编辑器中的项目。 使用“查看”菜单或在“项目资源管理器”中单击鼠标右键。
--------Click Here to display the illustration--------
--------点击此处显示插图--------
The default for a UserForm is to not display the form. So to make it visible (and make the controls on it available to the user), execute the Show method of the form. I added another form button just for this.
UserForm的默认设置是不显示该表单。 因此,要使其可见(并使其对用户可用),请执行表单的Show方法。 我为此添加了另一个表单按钮。
Sub Button2_Click()
UserForm1.Show
End Sub
You'll notice that the UserForm is modal by default. That means that when the form is active, everything else in the application is inactive. (Clicking the other buttons does nothing, for example.) You can change this by changing the ShowModal property of the UserForm to False. But this is getting us deeper into programming. The next articles in this series will explain more about this.
您会注意到,默认情况下,UserForm是模式的。 这意味着当表单处于活动状态时,应用程序中的其他所有内容均处于非活动状态。 (例如,单击其他按钮无效。)您可以通过将UserForm的ShowModal属性更改为False来更改此设置。 但这使我们更深入地进行编程。 本系列的下一篇文章将对此进行更多说明。
The code for the UserForm is placed in the UserForm object. If you select View Code for all of the objects in Project Explorer, you will see that there are three separate Click event subroutines that are contained in three different objects. But they're all available to the same workbook.
UserForm的代码放置在UserForm对象中。 如果为Project Explorer中的所有对象选择“查看代码”,则将看到三个不同的对象中包含三个单独的Click事件子例程。 但是它们都可用于同一工作簿。
--------Click Here to display the illustration--------
--------点击此处显示插图--------
In addition to forcing an event by clicking a button, VBA is also used to react to events in the objects in the hosting application. For example, you can detect when a spreadsheet changes in Excel. Or you can detect when a row is added to a database in Access and write a program to handle that event.
除了通过单击按钮强制事件外,VBA还用于对托管应用程序中对象中的事件做出React。 例如,您可以检测电子表格何时在Excel中更改。 或者,您可以在Access中检测何时将行添加到数据库中并编写程序来处理该事件。
In addition to the familiar command buttons, text boxes, and other components that you see in programs all the time, you can add components that are actually part of your Excel spreadsheet in your Word document. Or do the reverse. This goes way beyond "copy and paste". For example, you can show an Excel spreadsheet in a Word document.
除了您经常在程序中看到的熟悉的命令按钮,文本框和其他组件外,您还可以在 Word文档中添加实际上属于Excel电子表格的组件。 或相反。 这超出了“复制和粘贴”的范围。 例如,您可以在Word文档中显示Excel电子表格。
VBA allows you to use the whole power of one Office application in another. For example, Word has relatively simple calculation ability built in. But Excel - well - "excels" at calculation. Suppose you wanted to use the natural log of the Gamma function (a relatively sophisticated math calculation) in your Word document? With VBA, you can pass values to that function in Excel and get the answer back in your Word document.
VBA允许您在另一个Office应用程序中使用全部功能。 例如,Word内置了相对简单的计算功能。但是Excel-很好-在计算上“出色”。 假设您要在Word文档中使用Gamma函数的自然对数(相对复杂的数学计算)? 使用VBA,您可以将值传递给Excel中的该函数,并将答案返回到Word文档中。
And you can use much more than the Office applications! If you click the "More Controls" icon, you can see a considerable list of things that are installed on your computer. Not all of these work "out of the box" and you should have the documentation for each of them available, but it gives you an idea about how broad the support is for VBA.
您可以使用比Office应用程序更多的功能! 如果单击“更多控件”图标,则可以看到计算机上已安装的事物的相当多的列表。 并非所有这些工作都是“开箱即用”的,您应该拥有每个文件的文档,但是它可以使您了解对VBA的支持范围。
Of all the features in VBA, there is one that is clearly more useful than any other. Find out what it is on the next page.
在VBA的所有功能中,有一项功能显然比其他功能更有用。 在下一页中查找内容。
I've saved the best for last! Here's a technique that applies across the board to all of the Office applications. You'll find yourself using it a lot so we're covering it here in the Introduction.
我把最好的留了下来! 这是一种适用于所有Office应用程序的技术。 您会发现自己经常使用它,因此我们将在简介中对其进行介绍。
As you start to code more sophisticated VBA programs, one of the first problems you will run into is how to find out about methods and properties of Office objects. If you're writing a VB.NET program, you'll often look for code samples and examples to solve this problem. But when you consider all the different hosting applications and the fact that each of them have hundreds of new objects, you usually can't find something that exactly matches what you need to do.
当您开始编写更复杂的VBA程序代码时,您会遇到的第一个问题是如何找到Office对象的方法和属性。 如果您正在编写VB.NET程序,则通常会查找代码示例和示例来解决此问题。 但是,当您考虑所有不同的托管应用程序以及它们每个都有数百个新对象的事实时,通常找不到与您需要做的事情完全匹配的东西。
The answer is the "Record Macro ..."
答案是“记录宏...”
The basic idea is to turn on "Record Macro," go through the steps of a process that is similar to what you want your program to accomplish, and then check the resulting VBA program for code and ideas.
基本思路是打开“记录宏”,执行与您希望程序完成的过程类似的过程,然后检查生成的VBA程序中的代码和想法。
Many people make the mistake of thinking that you have to be able to record exactly the program you need. But it's not at all necessary to be that exact. It's usually good enough to record a VBA program that is just "close" to what you want and then add the code modifications to make it do the job precisely. It's so easy and useful that I will sometimes record a dozen programs with slight differences just to see what the code differences are in the result. Remember to delete all the experiments when you're finished looking at them!
许多人误以为您必须能够准确记录所需的程序。 但这并不需要那么精确。 通常足以录制一个与您想要的“接近”的VBA程序,然后添加代码修改以使其准确地完成工作。 它是如此简单和有用,以至于我有时会记录一打有细微差异的程序,只是为了查看结果中的代码差异。 完成实验后,请记住删除所有实验!
As an example, I clicked Record Macro in the Word Visual Basic Editor and typed several lines of text. Here's the result. (Line continuations have been added to make them shorter.)
例如,我在Word Visual Basic编辑器中单击“记录宏”,然后键入几行文本。 这是结果。 (添加了行连续以使其更短。)
Sub Macro1()
'
' Macro1 Macro
'
'
Selection.TypeText Text:= _
"These are the times that "
Selection.TypeText Text:= _
"try men's souls. The "
Selection.TypeText Text:= _
"summer soldier"
Selection.TypeText Text:= _
" and the sunshine patriot "
Selection.TypeText Text:= _
"will, in these times, shrink from "
Selection.TypeText Text:= _
"the service of their country."
Selection.MoveUp Unit:=wdLine, Count:=1
Selection.HomeKey Unit:=wdLine
Selection.MoveRight Unit:=wdCharacter, _
Count:=5, Extend:=wdExtend
Selection.Font.Bold = wdToggle
End Sub
Nobody studies VBA just for itself. You always use it along with a specific Office application. So, to continue learning, there are articles here that demonstrate VBA used with both Word and Excel:
没有人会为自己学习VBA。 您始终将其与特定的Office应用程序一起使用。 因此,为了继续学习,此处有一些文章演示了Word和Excel一起使用的VBA:
-> Getting Started Using VBA: The Word Working Partner
->使用VBA入门:Word工作伙伴
-> Getting Started Using VBA: The Excel Working Partner
->使用VBA入门:Excel工作伙伴