Đề Xuất 4/2023 # Office Space: From Vba Macro To Word Add # Top 12 Like | Beiqthatgioi.com

Đề Xuất 4/2023 # Office Space: From Vba Macro To Word Add # Top 12 Like

Cập nhật nội dung chi tiết về Office Space: From Vba Macro To Word Add mới nhất trên website Beiqthatgioi.com. Hy vọng thông tin trong bài viết sẽ đáp ứng được nhu cầu ngoài mong đợi của bạn, chúng tôi sẽ làm việc thường xuyên để cập nhật nội dung mới nhằm giúp bạn nhận được thông tin nhanh chóng và chính xác nhất.

Office Space

From VBA Macro to Word Add-in

Robert Bogue

Code download available at: OfficeSpace2008_05.exe(166 KB)


Book Learning Macro Basics Moving Macros to VSTO Writing New Add-In Code More Buttons

Document automation isn’t a new functionality by any means. It has been going on since the invention of macros, and there has been a full-fledged programming model within Microsoft® Office applications since the early 1990s. For many years, the Office tools have featured macro recorders that weren’t limited to simply replaying keystrokes but have been capable of writing code on the fly as well. Macros have even demonstrated that they are functional enough to write viruses. And while writing a virus using a Word macro may be a dubious feat, it is a feat nonetheless.

However, even with all of the capabilities of Visual Basic® for Applications (VBA), there are some things it just doesn’t do very well. In the early days of VBA, XML hadn’t yet been invented, the Internet was in its infancy, and the first HTML pages were just beginning to appear. As such, it’s no wonder that making a Web service call isn’t well handled in the context of Visual Basic for Applications.

The Microsoft .NET Framework CLR, on the other hand, understands these technologies quite well. The ability to call Web services is just one among a number of reasons for wanting to write .NET-targeted code rather than VBA-and doing so means using Visual Studio® Tools for Office (VSTO). But switching from VBA to VSTO doesn’t have to be a case of throwing the baby out with the bath water; rather, it can be just a natural way to extend how you are already developing solutions in Office.

In this column you’ll see how to use Word to capture some VBA code that solves a basic problem. Then I will use the latest version of VSTO included with Visual Studio 2008 to wrap this code into a deployable Word add-in. I’ll also write some simple code for some of the tasks that the macro recorder either just can’t record or doesn’t record in an optimal way.

Book Learning

Recently, I found myself in a situation where this kind of VBA-to-VSTO conversion was perfect for the problem at hand. I was finishing my latest book, The SharePoint Shepherd’s Guide for End Users. The book is self-published, and I needed to output the manuscript from Word into a PDF that the printer could use. For that to work, there were several steps I first needed to complete to get the manuscript ready.

First, I had to assemble multiple files into one large document. With more than 140 individual files representing 13 sections and 116 tasks, munging them together wasn’t something I wanted to do by hand. Having so many individual files was great when working with Microsoft SharePoint® because it allowed for individual tracking of each task through the editorial workflow, but the sheer number made assembly a task best handled by automation.

Second, I wanted to make sure that all of the tracked changes in all of the documents had been accepted. During the editing process, I used revision marks (via the Track Changes feature in Word) to keep track of editing and other changes to the manuscript. The revision marks are supposed to all be accepted as part of the final checkout of the content, but if I missed some, the formatting of the revision marks would stand out in the final book, which wouldn’t be very professional looking.

I am going to illuminate the process of creating each of these pieces and the relative ability of the macro recorder to capture the code needed for each function. I’ll start by using the recorder to generate the basic automation code. From there I’ll take a closer look at workable but sub-optimal generated code. Finally, I’ll look at the recorder not generating code at all. I’ll convert the VBA code into VSTO code and put it into a Word add-in that I can use to assemble the final book. Just to make the process more challenging, I’ll convert the code from VBA to C# in the course of bringing it into VSTO.

Macro Basics

Figure 1** Enabling the Developer Tab in the Ribbon **

Figure 2** Record a Macro from the Developer Tab **

Figure 3** Naming the Macro **

Figure 4 AddFiles VBA Macro

Sub AddFiles() ' ' AddFiles Macro ' ' ChangeFileOpenDirectory _ "https://sharepoint.contoso.com/sites/sharepoint/" & _ "Shared%20Documents/SharePoint%20Tasks/" chúng tôi fileName:= _ "https://sharepoint.contoso.com/sites/SharePoint/" & _ "Shared%20Documents/SharePoint%20Tasks/" & _ "Task001%20-%20Create%20a%20Team%20Web%20Site.docx", _ ConfirmConversions:=False, _ ReadOnly:=False, _ AddToRecentFiles:=False, _ PasswordDocument:="", _ PasswordTemplate:="", _ Revert:=False, _ WritePasswordDocument:="", _ WritePasswordTemplate:="", _ Format:= wdOpenFormatAuto, _ XMLTransform:="" Selection.WholeStory chúng tôi chúng tôi Template:="Normal", NewTemplate:=False, DocumentType:=0 Selection.PasteAndFormat (wdPasteDefault) End Sub

Notice that there is an extraneous line that resets the next File Open directory. After that you see the Open command, and then there’s the series of commands to copy the text, create a new document, and paste the text into the new document. The code that the macro recording produced isn’t perfect, but it isn’t bad either. So I’ll take that, enhance it, and put it into VSTO.

Moving Macros to VSTO

To get started with VSTO, I first create a Word 2007 Add-in project. I open Visual Studio, start a new project, use the Word 2007 Add-in template for the project, and name the project PublishPrep. Upon successful creation of the new VSTO project, your Visual Studio 2008 environment should look similar to Figure 5.

Figure 5** New Word Add-In Project **

With the project created, I need to create a way for users to access the functionality in the add-in. For 2007 Office system applications, that means creating a Ribbon tab and buttons. First, add a new item to your project and select the Ribbon (Visual Designer) template from the Add New Item dialog. Name your new ribbon PublishPrep.

The next step is to customize the Ribbon. In this case, I’m just going to create a group that will live on the Add-ins tab instead of adding my own tab to the Ribbon. My group will contain three buttons.

Figure 6** Configuring the PublishPrep Ribbon **

Open the toolbox, scroll down to the Office Ribbon Controls group, and drag three button controls over onto the Publishing Preparation group. Note that the buttons will stack vertically by default.

Figure 7** Buttons and Group Configured for the Add-In **

Writing New Add-In Code

The first part of the code, a function called AppendFile (see Figure 8), takes a single parameter, the file name. At a quick glance the code doesn’t resemble the code the macro recorder wrote for me, but that’s mostly an illusion.

Figure 8 AppendFile

void AppendFile(string file) { if (string.IsNullOrEmpty(file)) return; Application app = Globals.ThisAddIn.Application; Document activeDoc = app.ActiveDocument; if (activeDoc == null) return; object fileObj = file; object confirmConversions = false; object readOnly = true; object addToRecentFiles = false; object passwordDocument = Missing.Value; object passwordTemplate = Missing.Value; object revert = true; object writePasswordDocument = Missing.Value; object writePasswordTemplate = Missing.Value; object format = Missing.Value; object encoding = Missing.Value; object visible = false; object openAndRepair = false; object documentDirection = Missing.Value; object noEncodingDialog = Missing.Value; object xMLTransform = Missing.Value; Document newDoc = app.Documents.Open(ref fileObj, ref confirmConversions, ref readOnly, ref addToRecentFiles, ref passwordDocument, ref passwordTemplate, ref revert, ref writePasswordDocument, ref writePasswordTemplate, ref format, ref encoding, ref visible, ref openAndRepair, ref documentDirection, ref noEncodingDialog, ref xMLTransform); app.Selection.WholeStory(); app.Selection.Copy(); activeDoc.Select(); object collapseEnd = WdCollapseDirection.wdCollapseEnd; app.Selection.Collapse(ref collapseEnd); app.Selection.Paste(); object saveChanges = WdSaveOptions.wdDoNotSaveChanges; object originalFormat = WdOpenFormat.wdOpenFormatAuto; object routeDocument = Missing.Value; newDoc.Close(ref saveChanges, ref originalFormat, ref routeDocument); object breakType = WdBreakType.wdPageBreak; app.Selection.InsertBreak(ref breakType); }

The first four lines just get the active document and perform error checking. If there’s no active document, you can’t exactly append to it, and if you don’t have a file name to append, there’s not much more you can do. The other thing that these lines are doing is getting references to the application-which is assumed in VBA-and the active document when the button method was called, something the recorded version of the macro didn’t need to do.

The next set of lines-the object variable declarations-are necessary because of the way C# makes the call to the COM components that Word exposes. I need to specify missing values, and since the values are all passed by reference, I need a variable to hold them.

The code then performs the same copy operation that the macro recorder generated. The real difference here is that my add-in code is responsible for the management of the active document, including making sure that the cursor position is set to the end of the active document.

The final block of code closes the document I opened, making sure not to save any changes. It also adds a page break after the inserted content because I want to make sure that the contents of the individual files don’t run together.

The second part of the code actually gets the list of files to assemble and calls AppendFile (see Figure 9). This isn’t code that the macro recorder captured, but it is where you see the power of VSTO because it allows you to leverage all of the .NET constructs. In this case, I’ll leverage the OpenFileDialog control, the ability to open and read from a text file, the use of generics to create a list of files, and calling another smaller method that iterates through the list.

Figure 9 VSTO Power Behind the Button

using Microsoft.Office.Interop.Word; using chúng tôi using System.Reflection;

Finally, replace the method stub created by Visual Studio with the code in Figure 9.

More Buttons

Figure 10** Enabling the Developer Tab in the Ribbon **

Sub AcceptAllChanges() ' ' AcceptAllChanges Macro ' WordBasic.AcceptAllChangesInDoc End Sub

The macro recorder recorded this action to use the WordBasic object. The WordBasic object is a holdover from before Word macros were modified to use VBA. It’s not the best way to approach the problem. It’s much better to use ActiveDocument. You can either employ the AcceptAllRevisions method or the Revision property’s AcceptAll method. I slightly prefer the Revisions.AcceptAll nomenclature, but either method works.

Here is the code necessary to accept revisions from within VSTO code:

One interesting thing to note is that the indexer here is 1-based, not zero-based as you would expect in C#.

Robert Bogue, Microsoft MVP for Microsoft Office Sharepoint Server, MCSE, and MCSA:Security, has contributed to more than 100 book projects and numerous other publishing projects. Robert blogs at chúng tôi you can reach him at Rob.Bogue@thorprojects.com. Find out more about his latest book project, The SharePoint Shepherd’s Guide for End Users, at sharepointshepherd.com.

Getting Started With Vba In Office

You can perform these tasks and accomplish a great deal more by using Visual Basic for Applications (VBA) for Office-a simple, but powerful programming language that you can use to extend Office applications.

This article is for experienced Office users who want to learn about VBA and who want some insight into how programming can help them to customize Office.

Beyond the power of scripting VBA to accelerate every-day tasks, you can use VBA to add new functionality to Office applications or to prompt and interact with the user of your documents in ways that are specific to your business needs. For example, you could write some VBA code that displays a pop up message that reminds users to save a document to a particular network drive the first time they try to save it.

This article explores some of the primary reasons to leverage the power of VBA programming. It explores the VBA language and the out-of-the-box tools that you can use to work with your solutions. Finally, it includes some tips and ways to avoid some common programming frustrations and missteps.


Interested in developing solutions that extend the Office experience across multiple platforms? Check out the new Office Add-ins model. Office Add-ins have a small footprint compared to VSTO Add-ins and solutions, and you can build them by using almost any web programming technology, such as HTML5, JavaScript, CSS3, and XML.

When to use VBA and why

There are several principal reasons to consider VBA programming in Office.

Automation and repetition

VBA is effective and efficient when it comes to repetitive solutions to formatting or correction problems. For example, have you ever changed the style of the paragraph at the top of each page in Word? Have you ever had to reformat multiple tables that were pasted from Excel into a Word document or an Outlook email? Have you ever had to make the same change in multiple Outlook contacts?

If you have a change that you have to make more than ten or twenty times, it may be worth automating it with VBA. If it is a change that you have to do hundreds of times, it certainly is worth considering. Almost any formatting or editing change that you can do by hand, can be done in VBA.

Extensions to user interaction

There are times when you want to encourage or compel users to interact with the Office application or document in a particular way that is not part of the standard application. For example, you might want to prompt users to take some particular action when they open, save, or print a document.

Interaction between Office applications

Do you need to copy all of your contacts from Outlook to Word and then format them in some particular way? Or, do you need to move data from Excel to a set of PowerPoint slides? Sometimes simple copy and paste does not do what you want it to do, or it is too slow. You can use VBA programming to interact with the details of two or more Office applications at the same time and then modify the content in one application based on the content in another.

Doing things another way

VBA programming is a powerful solution, but it is not always the optimal approach. Sometimes it makes sense to use other ways to achieve your aims.

The critical question to ask is whether there is an easier way. Before you begin a VBA project, consider the built-in tools and standard functionalities. For example, if you have a time-consuming editing or layout task, consider using styles or accelerator keys to solve the problem. Can you perform the task once and then use CTRL+Y (Redo) to repeat it? Can you create a new document with the correct format or template, and then copy the content into that new document?

Office applications are powerful; the solution that you need may already be there. Take some time to learn more about Office before you jump into programming.

Before you begin a VBA project, ensure that you have the time to work with VBA. Programming requires focus and can be unpredictable. Especially as a beginner, never turn to programming unless you have time to work carefully. Trying to write a “quick script” to solve a problem when a deadline looms can result in a very stressful situation. If you are in a rush, you might want to use conventional methods, even if they are monotonous and repetitive.

VBA Programming 101

Using code to make applications do things

You might think that writing code is mysterious or difficult, but the basic principles use every-day reasoning and are quite accessible. Microsoft Office applications are created in such a way that they expose things called objects that can receive instructions, in much the same way that a phone is designed with buttons that you use to interact with the phone. When you press a button, the phone recognizes the instruction and includes the corresponding number in the sequence that you are dialing. In programming, you interact with the application by sending instructions to various objects in the application. These objects are expansive, but they have their limits. They can only do what they are designed to do, and they will only do what you instruct them to do.

For example, consider the user who opens a document in Word, makes a few changes, saves the document, and then closes it. In the world of VBA programming, Word exposes a Document object. By using VBA code, you can instruct the Document object to do things such as Open, Save, or Close.

The following section discusses how objects are organized and described.

The Object Model

Developers organize programming objects in a hierarchy, and that hierarchy is called the object model of the application. Word, for example, has a top-level Application object that contains a Document object. The Document object contains Paragraph objects and so on. Object models roughly mirror what you see in the user interface. They are a conceptual map of the application and its capabilities.

The definition of an object is called a class, so you might see these two terms used interchangeably. Technically, a class is the description or template that is used to create, or instantiate, an object.

Once an object exists, you can manipulate it by setting its properties and calling its methods. If you think of the object as a noun, the properties are the adjectives that describe the noun and the methods are the verbs that animate the noun. Changing a property changes some quality of appearance or behavior of the object. Calling one of the object methods causes the object to perform some action.

The VBA code in this article runs against an open Office application where many of the objects that the code manipulates are already up and running; for example, the Application itself, the Worksheet in Excel, the Document in Word, the Presentation in PowerPoint, the Explorer and Folder objects in Outlook. Once you know the basic layout of the object model and some key properties of the Application that give access to its current state, you can start to extend and manipulate that Office application with VBA in Office.


In Word, for example, you can change the properties and invoke the methods of the current Word document by using the ActiveDocument property of the Application object. This ActiveDocument property returns a reference to the Document object that is currently active in the Word application. “Returns a reference to” means “gives you access to.”

The following code does exactly what it says; that is, it saves the active document in the application.


Read the code from left to right, “In this Application, with the Document referenced by ActiveDocument, invoke the Save method.” Be aware that Save is the simplest form of method; it does not require any detailed instructions from you. You instruct a Document object to Save and it does not require any more input from you.

If a method requires more information, those details are called parameters. The following code runs the SaveAs method, which requires a new name for the file.

Application.ActiveDocument.SaveAs ("New Document Name.docx")

Values listed in parentheses after a method name are the parameters. Here, the new name for the file is a parameter for the SaveAs method.


You use the same syntax to set a property that you use to read a property. The following code executes a method to select cell A1 in Excel and then to set a property to put something in that cell.

Application.ActiveSheet.Range("A1").Select Application.Selection.Value = "Hello World"

The first challenge in VBA programming is to get a feeling for the object model of each Office application and to read the object, method, and property syntax. The object models are similar in all Office applications, but each is specific to the kind of documents and objects that it manipulates.

In the first line of the code snippet, there is the Application object, Excel this time, and then the ActiveSheet, which provides access to the active worksheet. After that is a term not as familiar, Range, which means “define a range of cells in this way.” The code instructs Range to create itself with just A1 as its defined set of cells. In other words, the first line of code defines an object, the Range, and runs a method against it to select it. The result is automatically stored in another property of the Application called Selection.

The second line of code sets the Value property of Selection to the text “Hello World”, and that value appears in cell A1.

The simplest VBA code that you write might simply gain access to objects in the Office application that you are working with and set properties. For example, you could get access to the rows in a table in Word and change their formatting in your VBA script.

That sounds simple, but it can be incredibly useful; once you can write that code, you can harness all of the power of programming to make those same changes in several tables or documents, or make them according to some logic or condition. For a computer, making 1000 changes is no different from making 10, so there is an economy of scale here with larger documents and problems, and that is where VBA can really shine and save you time.

Macros and the Visual Basic Editor

Now that you know something about how Office applications expose their object models, you are probably eager to try calling object methods, setting object properties, and responding to object events. To do so, you must write your code in a place and in a way that Office can understand; typically, by using the Visual Basic Editor. Although it is installed by default, many users do not know that it is even available until it is enabled on the ribbon.

All Office applications use the ribbon. One tab on the ribbon is the Developer tab, where you access the Visual Basic Editor and other developer tools. Because Office does not display the Developer tab by default, you must enable it by using the following procedure:

To enable the Developer tab

On the File tab, choose Options to open the Options dialog box.

Choose Customize Ribbon on the left side of the dialog box.

Under Choose commands from on the left side of the dialog box, select Popular Commands.

Under Customize the Ribbon on the right side of the dialog box, select Main Tabs in the drop down list box, and then select the Developer checkbox.

Choose OK.


In Office 2007, you displayed the Developer tab by choosing the Office button, choosing Options, and then selecting the Show Developer tab in Ribbon check box in the Popular category of the Options dialog box.

After you enable the Developer tab, it is easy to find the Visual Basic and Macros buttons.

Figure 1. Buttons on the Developer tab

Security issues

To protect Office users against viruses and dangerous macro code, you cannot save macro code in a standard Office document that uses a standard file extension. Instead, you must save the code in a file with a special extension. For example you cannot save macros in a standard Word document with a .docx extension; instead, you must use a special Word Macro-Enabled Document with a .docm extension.

When you open a .docm file, Office security might still prevent the macros in the document from running, with or without telling you. Examine the settings and options in the Trust Center on all Office applications. The default setting disables macro from running, but warns you that macros have been disabled and gives you the option to turn them back on for that document.

You can designate specific folders where macros can run by creating Trusted Locations, Trusted Documents, or Trusted Publishers. The most portable option is to use Trusted Publishers, which works with digitally signed documents that you distribute. For more information about the security settings in a particular Office application, open the Options dialog box, choose Trust Center, and then choose Trust Center Settings.


Some Office applications, like Outlook, save macros by default in a master template on your local computer. Although that strategy reduces the local security issues on your own computer when you run your own macros, it requires a deployment strategy if you want to distribute your macro.

Recording a macro

When you choose the Macro button on the Developer tab, it opens the Macros dialog box, which gives you access to VBA subroutines or macros that you can access from a particular document or application. The Visual Basic button opens the Visual Basic Editor, where you create and edit VBA code.

Another button on the Developer tab in Word and Excel is the Record Macro button, which automatically generates VBA code that can reproduce the actions that you perform in the application. Record Macro is a terrific tool that you can use to learn more about VBA. Reading the generated code can give you insight into VBA and provide a stable bridge between your knowledge of Office as a user and your knowledge as a programmer. The only caveat is that the generated code can be confusing because the Macro editor must make some assumptions about your intentions, and those assumptions are not necessarily accurate.

To record a macro

Open Excel to a new Workbook and choose the Developer tab in the ribbon. Choose Record Macro and accept all of the default settings in the Record Macro dialog box, including Macro1 as the name of the macro and This Workbook as the location.

Choose OK to begin recording the macro. Note how the button text changes to Stop Recording. Choose that button the instant you complete the actions that you want to record.

Choose cell B1 and type the programmer’s classic first string: Hello World. Stop typing and look at the Stop Recording button; it is grayed out because Excel is waiting for you to finish typing the value in the cell.

Choose cell B2 to complete the action in cell B1, and then choose Stop Recording.

Choose Macros on the Developer tab, select Macro1 if it is not selected, and then choose Edit to view the code from Macro1 in the Visual Basic Editor.

Figure 2. Macro code in Visual Basic Editor

Looking at the code

The macro that you created should look similar to the following code.

Sub Macro1() ' ' Macro1 Macro ' ' Range("B1").Select ActiveCell.FormulaR1C1 = "Hello World" Range("B2").Select End Sub

Be aware of the similarities to the earlier code snippet that selected text in cell A1, and the differences. In this code, cell B1 is selected, and then the string “Hello World” is applied to the cell that has been made active. The quotes around the text specify a string value as opposed to a numeric value.

Remember how you chose cell B2 to display the Stop Recording button again? That action shows up as a line of code as well. The macro recorder records every keystroke.

When the macro recorder generates the code, it uses a complex algorithm to determine the methods and the properties that you intended. If you do not recognize a given property, there are many resources available to help you. For example, in the macro that you recorded, the macro recorder generated code that refers to the FormulaR1C1 property. Not sure what that means?


Be aware that Application object is implied in all VBA macros. The code that you recorded works with Application. at the beginning of each line.

Using Developer Help

Select FormulaR1C1 in the recorded macro and press F1. The Help system runs a quick search, determines that the appropriate subjects are in the Excel Developer section of the Excel Help, and lists the FormulaR1C1 property. You can choose the link to read more about the property, but before you do, be aware of the Excel Object Model Reference link near the bottom of the window. Choose the link to view a long list of objects that Excel uses in its object model to describe the Worksheets and their components.

Choose any one of those to see the properties and methods that apply to that particular object, along with cross references to different related options. Many Help entries also have brief code examples that can help you. For example, you can follow the links in the Borders object to see how to set a border in VBA.

Worksheets(1).Range("A1").Borders.LineStyle = xlDouble

Editing the code

The Borders code looks different from the recorded macro. One thing that can be confusing with an object model is that there is more than one way to address any given object, cell A1 in this example.

Sometimes the best way to learn programming is to make minor changes to some working code and see what happens as a result. Try it now. Open Macro1 in the Visual Basic Editor and change the code to the following.

Sub Macro1() Worksheets(1).Range("A1").Value = "Wow!" Worksheets(1).Range("A1").Borders.LineStyle = xlDouble End Sub


Use Copy and Paste as much as possible when working with code to avoid typing errors.

You do not need to save the code to try it out, so return to the Excel document, choose Macros on the Developer tab, choose Macro1, and then choose Run. Cell A1 now contains the text Wow! and has a double-line border around it.

Figure 3. Results of your first macro

You just combined macro recording, reading the object model documentation, and simple programming to make a VBA program that does something. Congratulations!

Did not work? Read on for debugging suggestions in VBA.

Programming tips and tricks

Start with examples

The VBA community is very large; a search on the Web can almost always yield an example of VBA code that does something similar to what you want to do. If you cannot find a good example, try to break the task down into smaller units and search on each of those, or try to think of a more common, but similar problem. Starting with an example can save you hours of time.

That does not mean that free and well-thought-out code is on the Web waiting for you to come along. In fact, some of the code that you find might have bugs or mistakes. The idea is that the examples you find online or in VBA documentation give you a head start. Remember that learning programming requires time and thought. Before you get in a big rush to use another solution to solve your problem, ask yourself whether VBA is the right choice for this problem.

Make a simpler problem

Programming can get complex quickly. It is critical, especially as a beginner, that you break the problem down to the smallest possible logical units, then write and test each piece in isolation. If you have too much code in front of you and you get confused or muddled, stop and set the problem aside. When you come back to the problem, copy out a small piece of the problem into a new module, solve that piece, get the code working, and test it to ensure that it works. Then move on to the next part.

Bugs and debugging

There are two main types of programming errors: syntax errors, which violate the grammatical rules of the programming language, and run-time errors, which look syntactically correct, but fail when VBA attempts to execute the code.

Although they can be frustrating to fix, syntax errors are easy to catch; the Visual Basic Editor beeps and flashes at you if you type a syntax error in your code.

For example, string values must be surrounded by double quotes in VBA. To find out what happens when you use single quotes instead, return to the Visual Basic Editor and replace the “Wow!” string in the code example with ‘Wow!’ (that is, the word Wow enclosed in single quotes). If you choose the next line, the Visual Basic Editor reacts. The error “Compile error: Expected: expression” is not that helpful, but the line that generates the error turns red to tell you that you have a syntax error in that line and as a result, this program will not run.

Choose OK and change the text back to”Wow!”.

Runtime errors are harder to catch because the programming syntax looks correct, but the code fails when VBA tries to execute it.

For example, open the Visual Basic Editor and change the Value property name to ValueX in your Macro, deliberately introducing a runtime error since the Range object does not have a property called ValueX. Go back to the Excel document, open the Macros dialog box and run Macro1 again. You should see a Visual Basic message box that explains the run-time error with the text, “Object doesn’t support this property of method.” Although that text is clear, choose Debug to find out more.

When you return to the Visual Basic Editor, it is in a special debug mode that uses a yellow highlight to show you the line of code that failed. As expected, the line that includes the ValueX property is highlighted.

You can make changes to VBA code that is running, so change ValueX back to Value and choose the little green play button underneath the Debug menu. The program should run normally again.

It is a good idea to learn how to use the debugger more deliberately for longer, more complex programs. At a minimum, learn a how to set break-points to stop execution at a point where you want to take a look at the code, how to add watches to see the values of different variables and properties as the code runs, and how to step through the code line by line. These options are all available in the Debug menu and serious debugger users typically memorize the accompanying keyboard shortcuts.

Using reference materials well

To open the Developer Reference that is built into Office Help, open the Help reference from any Office application by choosing the question mark in the ribbon or by pressing F1. Then, to the right of the Search button, choose the dropdown arrow to filter the contents. Choose Developer Reference. If you do not see the table of contents in the left panel, choose the little book icon to open it, and then expand the Object Model Reference from there.

Of course the Microsoft Office Developer Center is an excellent portal for articles, tips, and community information.

Searching forums and groups

All programmers get stuck sometimes, even after reading every reference article they can find and losing sleep at night thinking about different ways to solve a problem. Fortunately, the Internet has fostered a community of developers who help each other solve programming problems.

Any search on the Web for “office developer forum” reveals several discussion groups. You can search on “office development” or a description of your problem to discover forums, blog posts, and articles as well.

If you have done everything that you can to solve a problem, do not be afraid to post your question to a developers forum. These forums welcome posts from newer programmers and many of the experienced developers are glad to help.

The following are a few points of etiquette to follow when you post to a developer forum:

Before you post, look on the site for an FAQ or for guidelines that members want you to follow. Ensure that you post content that is consistent with those guidelines and in the correct section of the forum.

Include a clear and complete code sample, and consider editing your code to clarify it for others if it is part of a longer section of code.

Describe your problem clearly and concisely, and summarize any steps that you have taken to solve the problem. Take the time to write your post as well as you can, especially if you are flustered or in a hurry. Present the situation in a way that will make sense to readers the first time that they read the problem statement.

Be polite and express your appreciation.

Going further with programming

Although this article is short and only scratches the surface of VBA and programming, it is hopefully enough to get you started.

This section briefly discusses a few more key topics.


In the simple examples in this article you manipulated objects that the application had already created. You might want to create your own objects to store values or references to other objects for temporary use in your application. These are called variables.

To use a variable in VBA, must tell VBA which type of object the variable represents by using the Dim statement. You then set its value and use it to set other variables or properties.

Dim MyStringVariable As String MyStringVariable = "Wow!" Worksheets(1).Range("A1").Value = MyStringVariable

Branching and looping

The simple programs in this article execute one line at a time, from the top down. The real power in programming comes from the options that you have to determine which lines of code to execute, based on one or more conditions that you specify. You can extend those capabilities even further when you can repeat an operation many times. For example, the following code extends Macro1.

Sub Macro1() If Worksheets(1).Range("A1").Value = "Yes!" Then Dim i As Integer For i = 2 To 10 Worksheets(1).Range("A" & i).Value = "OK! " & i Next i Else MsgBox "Put Yes! in cell A1" End If End Sub

Type or paste the code into the Visual Basic Editor and then run it. Follow the directions in the message box that appears and change the text in cell A1 from Wow! to Yes! and run it again to see the power of looping. This code snippet demonstrates variables, branching and looping. Read it carefully after you see it in action and try to determine what happens as each line executes.

All of my Office applications: example code

Here are a few scripts to try; each solves a real-world Office problem.

Create an email in Outlook

Sub MakeMessage() Dim OutlookMessage As Outlook.MailItem Set OutlookMessage = Application.CreateItem(olMailItem) OutlookMessage.Subject = "Hello World!" OutlookMessage.Display Set OutlookMessage = Nothing End Sub

Be aware that there are situations in which you might want to automate email in Outlook; you can use templates as well.

Delete empty rows in an Excel worksheet

Sub DeleteEmptyRows() SelectedRange = Selection.Rows.Count ActiveCell.Offset(0, 0).Select For i = 1 To SelectedRange If ActiveCell.Value = "" Then Selection.EntireRow.Delete Else ActiveCell.Offset(1, 0).Select End If Next i End Sub

Be aware that you can select a column of cells and run this macro to delete all rows in the selected column that have a blank cell.

Delete empty text boxes in PowerPoint

Sub RemoveEmptyTextBoxes() Dim SlideObj As Slide Dim ShapeObj As Shape Dim ShapeIndex As Integer For Each SlideObj In ActivePresentation.Slides For ShapeIndex = SlideObj.Shapes.Count To 1 Step -1 Set ShapeObj = SlideObj.Shapes(ShapeIndex) If chúng tôi = msoTextBox Then If Trim(ShapeObj.TextFrame.TextRange.Text) = "" Then ShapeObj.Delete End If End If Next ShapeIndex Next SlideObj End Sub

Be aware that this code loops through all of the slides and deletes all text boxes that do not have any text. The count variable decrements instead of increments because each time the code deletes an object, it removes that object from the collection, which reduces the count.

Sub CopyCurrentContact() Dim OutlookObj As Object Dim InspectorObj As Object Dim ItemObj As Object Set OutlookObj = CreateObject("Outlook.Application") Set InspectorObj = OutlookObj.ActiveInspector Set ItemObj = InspectorObj.CurrentItem Application.ActiveDocument.Range.InsertAfter (ItemObj.FullName & " from " & ItemObj.CompanyName) End Sub

Be aware that this code copies the currently open contact in Outlook into the open Word document. This code only works if there is a contact currently open for inspection in Outlook.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Run Code From A Module In Excel Vba

1. Open the Visual Basic Editor.

3. Create a procedure (macro) called Cyan.





Note: a procedure is either a sub or a function. Learn more about functions and subs here, if you like.

4. The sub changes the background color of your worksheet to cyan. To achieve this, add the following code line.

Cells.Interior.ColorIndex = 28

Note: instead of ColorIndex number 28 (cyan), you can use any ColorIndex number.

To run the procedure, execute the following steps.


Note: code placed into a module is available to the whole workbook. That means you can select Sheet2 or Sheet3 and change the background color of these sheets as well. The Add a Macro to the Toolbar program illustrates how to make a macro available to all your workbooks (Excel files). Remember, code placed on a sheet (assigned to a command button) is only available for that particular sheet.

Bật Hoặc Tắt Macro Trong Các Tệp Office

Trong bài viết này

Bật macro khi Thanh Thông báo xuất hiện

Bật macro trong dạng xem Backstage

Bật macro một lần khi Cảnh báo Bảo mật xuất hiện

Thay đổi thiết đặt macro trong Trung tâm Tin cậy

Giải thích về các thiết đặt macro

Macro là gì, ai tạo ra chúng và có rủi ro nào về việc bảo mật?

Bật macro khi Thanh Thông báo xuất hiện

Khi bạn mở một tệp có macro, thanh thông báo màu vàng sẽ xuất hiện với biểu tượng lá chắn và nút Bật Nội dung. Nếu bạn biết chắc macro này đến từ một nguồn tin cậy, hãy làm theo các hướng dẫn sau đây:

Bật macro trong dạng xem Backstage

Một cách khác để bật macro trong một tệp là thông qua dạng xem Backstage trong Microsoft Office, dạng xem xuất hiện sau khi bạn bấm vào tab Tệp khi Thanh Thông báo màu vàng xuất hiện.

Bấm vào tab Tệp.

Bên dưới Bật Tất cả Nội dung, hãy bấm Luôn bật nội dung hiện hoạt của tài liệu này.Tệp trở thành tài liệu đáng tin cậy.

Bật macro một lần khi Cảnh báo Bảo mật xuất hiện

Bạn hãy làm theo các hướng dẫn sau đây để bật macro trong thời gian mở tệp. Khi bạn đóng và mở lại tệp này, cảnh báo sẽ xuất hiện lại.

Bấm vào tab Tệp.

Chọn Tùy chọn Nâng cao.

Bấm OK.

Thay đổi thiết đặt macro trong Trung tâm Tin cậy

Thiết đặt macro nằm trong Trung tâm Tin cậy. Tuy nhiên, nếu bạn làm việc trong một tổ chức, thì người quản trị hệ thống có thể đã thay đổi thiết đặt mặc định để ngăn không cho bất kỳ ai thay đổi các thiết đặt này.

Quan trọng: Khi bạn thay đổi thiết đặt macro của mình trong Trung tâm Tin cậy, chúng chỉ thay đổi đối với chương trình Office mà bạn hiện đang sử dụng. Thiết đặt macro đó không bị thay đổi đối với tất cả các chương trình Office.

Bấm tab Tệp.

Bấm Tùy chọn.

Chọn những lựa chọn mà bạn muốn.

Bấm OK.

Giải thích về các thiết đặt macro

Tắt tất cả các macro mà không thông báo Macro và các cảnh báo bảo mật về macro đều bị tắt.

Tắt tất cả các macro kèm theo thông báo Tắt macro nhưng các cảnh báo bảo mật vẫn xuất hiện khi có sự hiện diện của macro. Bật macro theo từng trường hợp.

Tắt tất cả macro trừ những macro được ký điện tử Tắt macro nhưng các cảnh báo bảo mật vẫn xuất hiện khi có sự hiện diện của macro. Tuy nhiên, nếu macro được ký điện tử bởi một người phát hành tin cậy, thì macro đó sẽ chạy nếu bạn đã tin tưởng người phát hành đó. Nếu bạn chưa tin tưởng người phát hành này, bạn sẽ được thông báo hãy bật macro đã ký và chọn tin tưởng người phát hành đó.

Bật tất cả các macro (không khuyến khích vì mã nguy hiểm có thể chạy) Tất cả các macro đều chạy. Thiết đặt này có thể khiến cho máy tính của bạn bị nguy hiểm khi gặp phải các mã độc hại.

Truy cập tin cậy vào mô hình đối tượng dự án VBA Cho phép hoặc không cho phép truy cập theo chương trình vào mô hình đối tượng Visual Basic for Applications (VBA) từ một chương trình tự động hóa. Tùy chọn bảo mật này dành cho mã được viết để tự động hóa một chương trình Office và thao tác với môi trường và mô hình đối tượng VBA. Đây là thiết đặt theo người dùng và theo ứng dụng, nó từ chối truy cập theo mặc định, ngăn không cho các chương trình trái phép tạo các mã độc hại tự sao lại. Để cho phép các chương trình tự động hóa truy cập vào mô hình đối tượng VBA, người dùng đang chạy mã này phải cấp quyền truy cập. Để bật chức năng truy cập, hãy chọn hộp kiểm này.

Lưu ý: Microsoft Publisher và Microsoft Access không có tùy chọn Truy nhập tin cậy vào đối tượng mô hình dự án VBA.

Macro là gì, ai tạo ra chúng và có rủi ro nào về việc bảo mật?

Trong bài viết này

Macro là gì và có rủi ro nào về bảo mật?

Bật hoặc tắt macro với Trung tâm Tin cậy

Bạn đang dùng chương trình nào?

Trung tâm Tin cậy có thể giúp bảo vệ tôi từ macro không an toàn như thế nào?

Cảnh báo bảo mật hỏi xem tôi muốn bật hay tắt macro. Tôi nên làm gì?

Macro là gì và có rủi ro nào về bảo mật?

Macro tự động hóa các tác vụ thường được sử dụng; nhiều macro được tạo bằng VBA và được viết bởi các nhà phát triển phần mềm. Tuy nhiên, một số macro có thể gây ra các nguy cơ bảo mật tiềm tàng. Một người có chủ định xấu có thể đặt một macro phá hoại vào một tài liệu hoặc tệp, macro này có thể lan sang một virus trên máy tính của bạn.

Bật hoặc tắt macro bằng Trung tâm Tin cậy

Cài đặt bảo mật macro nằm trong Trung tâm Tin cậy. Tuy nhiên, nếu bạn làm việc trong một tổ chức thì người quản trị hệ thống có thể đã thay đổi cài đặt mặc định để ngăn không cho bất kỳ ai thay đổi mọi thiết đặt.

Lưu ý: Khi bạn thay đổi thiết đặt macro của mình trong Trung tâm Tin cậy, chúng chỉ thay đổi đối với chương trình Office mà bạn hiện đang sử dụng. Thiết đặt macro đó không bị thay đổi đối với tất cả các chương trình Office.

Bạn đang dùng chương trình Hệ thống Microsoft Office 2007 nào?


Bấm Cài đặt Macro.

Bấm vào tùy chọn bạn muốn:

Không cảnh báo và tắt mọi macro Hãy bấm vào tùy chọn này nếu bạn không tin cậy macro. Tất cả các macro và cảnh báo bảo mật về macro đều sẽ bị tắt.

Cảnh báo cho mọi macro Bấm vào tùy chọn này nếu bạn muốn tắt macro nhưng vẫn muốn nhận cảnh báo bảo mật nếu có macro. Theo cách này, bạn có thể chọn thời điểm bật macro đó theo từng trường hợp.

Không kiểm tra bảo mật macro (Không khuyên dùng) Bấm tùy chọn này để cho phép chạy tất cả các macro. Cài đặt này khiến máy tính của bạn dễ bị mã độc hại tiềm ẩn tấn công, đồng thời, cài đặt này cũng không được khuyên dùng.

Đầu trang


Bấm Cài đặt Macro.

Đầu trang


Bấm Cài đặt Macro.

Đầu trang

Trung tâm Tin cậy có thể giúp bảo vệ tôi từ macro không an toàn như thế nào?

Trước khi bật macro trong tài liệu, Trung tâm Tin cậy sẽ kiểm tra thông tin sau đây:

Macro được ký bởi nhà phát triển với một chữ ký số.

Chữ ký điện tử đó hợp lệ.

Chữ ký điện tử đó còn hiệu lực (chưa hết hạn).

Chứng chỉ liên kết với chữ ký điện tử đó được phát hành bởi một cơ quan cấp chứng chỉ (CA) có uy tín.

Nhà phát triển ký macro là một người phát hành tin cậy.

Nếu Trung tâm Tin cậy phát hiện sự cố với bất kỳ thông tin nào trong số này, macro sẽ bị tắt theo mặc định và Thanh Thông báo sẽ xuất hiện để thông báo cho bạn biết về một macro không an toàn tiềm ẩn.

Để bật macro, hãy bấm Tùy chọn trên Thanh Thông báo, một hộp thoại bảo mật sẽ mở ra. Xem mục tiếp theo để biết thông tin về cách đưa ra quyết định cho macro và bảo mật.

Lưu ý: Trong Microsoft Office Outlook 2007 và Microsoft Office Publisher 2007, cảnh báo bảo mật sẽ xuất hiện trong các hộp thoại, chứ không phải trong Thanh Thông báo.

Đầu Trang

Cảnh báo bảo mật sẽ hỏi nếu tôi muốn bật hoặc tắt macro. Tôi nên làm gì?

Khi hộp thoại Tùy chọn Bảo mật xuất hiện, bạn có thể bật hoặc tắt macro. Bạn nên bật macro nếu chắc chắn macro được cung cấp từ một nguồn đáng tin cậy.

Quan trọng: Nếu bạn chắc chắn tài liệu và macro được cung cấp từ một nguồn đáng tin cậy và có chữ ký hợp lệ, đồng thời bạn không muốn nhận lại thông báo về chúng, thay vì việc thay đổi cài đặt Trung tâm Tin cậy mặc định thành một cài đặt bảo mật macro kém an toàn hơn, bạn có thể bấm vào Tin cậy tất cả các tài liệu từ nhà phát hành này trong hộp thoại bảo mật. Thao tác này sẽ thêm nhà phát hành vào Danh sách Nhà phát hành Tin cậy trong Trung tâm Tin cậy. Tất cả phần mềm từ nhà phát hành đó sẽ được tin cậy. Trong trường hợp macro không có chữ ký hợp lệ, nhưng bạn tin cậy và không muốn được thông báo lần nữa, thay vì thay đổi thiết đặt Trung tâm tin cậy mặc định sang thiết đặt bảo mật macro an toàn ít hơn, tốt hơn là bạn nên di chuyển tài liệu sang phần Thêm, loại bỏ hoặc thay đổi vị trí tin cậy. Tài liệu trong vị trí tin cậy được phép chạy mà không cần hệ thống bảo mật Trung tâm Tin cậy kiểm tra.

Tùy theo kịch bản mà hộp thoại bảo mật sẽ mô tả sự cố cụ thể. Bảng sau đây liệt kê các sự cố có thể xảy ra và đưa ra lời khuyên về những điều bạn nên hay không nên làm trong từng trường hợp.

Sự cố

Lời khuyên

Macro không được ký Vì macro chưa được ký điện tử nên không thể xác nhận danh tính người phát hành macro. Do đó, không thể xác định macro đó có an toàn hay không.

Trước khi bạn bật macro chưa được ký, hãy đảm bảo macro được cấp từ một nguồn đáng tin cậy. Bạn vẫn có thể làm việc trong tài liệu của mình, ngay cả khi bạn không bật macro.

Chữ ký macro không được tin cậy Macro có thể không an toàn vì macro đã được ký điện tử, chữ ký hợp lệ và bạn không quyết định tin tưởng nhà phát hành đã ký macro.

Bạn có thể sự tin cậy nhà phát hành macro một cách rõ ràng bằng cách bấm vào Tin cậy mọi tài liệu từ nhà phát hành này trong hộp thoại bảo mật. Tùy chọn này chỉ xuất hiện nếu chữ ký hợp lệ. Thao tác bấm vào tùy chọn này sẽ thêm nhà phát hành vào Danh sách Nhà phát hành Tin cậy trong Trung tâm Tin cậy.

Chữ ký macro không hợp lệ Macro có thể không an toàn vì macro đã được ký điện tử và chữ ký không hợp lệ.

Chúng tôi khuyên bạn không nên bật macro có chữ ký điện tử không hợp lệ. Chữ ký không hợp lệ có thể là do chữ kỹ đã bị xáo trộn.

Chữ ký macro đã hết hạn Macro có thể không an toàn vì macro đã được ký điện tử và chữ ký đã hết hạn.

Trước khi bật macro có chữ ký điện tử đã hết hạn, bạn hãy đảm bảo rằng macro được cấp một nguồn đáng tin cậy. Nếu bạn đã sử dụng tài liệu này trong quá khứ mà không gặp bất kỳ vấn đề gì về bảo mật thì việc bật macro có thể sẽ ít nguy hiểm hơn.

Bạn đang đọc nội dung bài viết Office Space: From Vba Macro To Word Add trên website Beiqthatgioi.com. Hy vọng một phần nào đó những thông tin mà chúng tôi đã cung cấp là rất hữu ích với bạn. Nếu nội dung bài viết hay, ý nghĩa bạn hãy chia sẻ với bạn bè của mình và luôn theo dõi, ủng hộ chúng tôi để cập nhật những thông tin mới nhất. Chúc bạn một ngày tốt lành!