Menu
-->
Are you facing a repetitive clean up of fifty tables in Word? Do you want a particular document to prompt the user for input when it opens? Are you having difficulty figuring out how to get your contacts from Microsoft Outlook into a Microsoft Excel spreadsheet efficiently?
Download latest Mac capable version of Excel-REST (v4.0.0-beta.1 in my case) Download drop-in alternative for Microsoft Dictionary (see VBA-Dictionary) Unzip both zip files; Open 'Excel-REST - Blank.xlsm” from Excel-REST folder; Right click on Excel for Mac 2011 ribbon and activate Developer tools. Use VBA add-ins and macros that you developed for Office for Windows with Office for Mac. Applies to: Excel for Mac PowerPoint for Mac Word for Mac Office 2016 for Mac. If you are authoring Macros for Office for Mac, you can use most of the same objects that are available in VBA for Office. Change the names and captions of the controls according to the table below. Names are used in the Excel VBA code. Captions are those that appear on your screen. It is good practice to change the names of controls. This will make your code easier to read. Microsoft Excel enables users to automate features and commands using macros and Visual Basic for Applications (VBA) scripting. VBA is the programming language Excel uses to create macros. It will also execute automated commands based on specific conditions. Macros are a series of pre-recorded commands.
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.
The Office suite of applications has a rich set of features. There are many different ways to author, format, and manipulate documents, email, databases, forms, spreadsheets, and presentations. The great power of VBA programming in Office is that nearly every operation that you can perform with a mouse, keyboard, or a dialog box can also be done by using VBA. Further, if it can be done once with VBA, it can be done just as easily a hundred times. (In fact, the automation of repetitive tasks is one of the most common uses of VBA in 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.
Note
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.
Methods
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.
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.
Properties
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.
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.
Note
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.
Note
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.
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.
The lines of code that start with an apostrophe and colored green by the editor are comments that explain the code or remind you and other programmers the purpose of the code. VBA ignores any line, or portion of a line, that begins with a single quote. Writing clear and appropriate comments in your code is an important topic, but that discussion is out of the scope of this article. Subsequent references to this code in the article do not include those four comment lines.
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?
Note
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.
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.
Tip
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 toValueX 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.
Figure 5. Filtering on developer Help applies to all Office applications
Time spent browsing the Object Model reference pays off. After you understand the basics of VBA syntax and the object model for the Office application that you are working with, you advance from guesswork to methodical programming.
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.
Variables
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.
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.
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
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
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
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.
Copy a contact from Outlook to Word
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.
for Microsoft Office Excel, Access & Word on Windows or Mac
IDAutomation VBA Barcode Functions and Macros allow easy generation of barcodes in Microsoft Office Suite applications such as Excel, Word and Access on both Windows® and Mac operating systems, compatible with Excel 2003 and greater in Windows and Excel 2011 and greater on Mac. The VBA modules are also compatible with legacy VB6.
Userform Excel Mac
These font encoders are used to format the
- Charles Daneri, Objective Systems, LLC (computer consulting firm), Baltimore, MD.
- Charles Daneri, Objective Systems, LLC (computer consulting firm), Baltimore, MD.
These Office Macros consist of pure VBA modules with customizable code, functions and other options that allow for dynamic and variable data barcode generation. Consequently, this also means that the implementation may be more complicated for the average user. These font encoder tools format data into a text string that will display a readable barcode when the appropriate IDAutomation font is applied to it.
The Macros are free to use with the purchase of any IDAutomation linear barcode font and are compatible with Microsoft Office 2000 and greater running on Windows® or Office 2004 and 2011 for Mac platforms. This tool is not compatible with Office 2008 for Mac because that version does not have VBA capability. IDAutomation has a variety of Mac Barcode Integration options for those using Microsoft Office 2008 for Mac. Mac users and those located outside of the US Western character set should use the IDAutomation Universal Barcode Font Advantage package with related Universal Font VBA functions for Code 128 and Interleaved 2 of 5 fonts.
Importing and Exporting VBA in Excel
The barcode Macros and functions reside inside the Excel file as a custom VBA module. To use these barcode functions in an Excel spreadsheet, the IDAutomationVBAmodule must be imported. If the IDAutomationVBA.bas file is not available for import, it may be exported from the sample spreadsheet provided in the downloaded file. With all 2D font packages, such as QR-Code and
- Thomas Bell, Cynosure, Westford, MA
- Thomas Bell, Cynosure, Westford, MA
How to Create a Barcode in Excel
- Enable the security setting that allows Macros to run. If prompted when the document re-opens, choose Enable Macros.
- Office 2007 and above applications require the Macros to run from a trusted location.
- Office 2004 and 2011 for Mac settings are located at Excel - Preferences - Security - Macro Security.
- Excel 2000 and 2003 require a medium-security setting to run Macros. Open Excel and set the security level to medium by choosing Tools - Macro - Security.
- Signed Macros are included in the latest version of the VBA Module download. Simply choose the Trust this Publisher option and the VBA Macros will run unprompted. Data may be pasted into these files and used if the Macros are not modified.
- If a different spreadsheet is used other than the sample provided, the Macros must be imported into the spreadsheet.
- Create a column in the spreadsheet for the barcode.
- Size the column to make sure it is wide enough to contain the entire barcode.
- Format the column so that any text appearing in it will be centered. This is necessary to create the white space (often called the quiet zone) before and after the barcode.
- Enter the formula in this cell that will format the data to the barcode font. If unsure which function or barcode to use, consider the Code 128 barcode fonts with the =Code128(B10,0) function where 'B10' refers to the cell location of the data that is to be encoded and the ',0' formats the result of the formula to the Code 128 fonts. For all 2D fonts, refer to the documentation within that particular package.
- Examine the spreadsheet to make sure the data is being properly formatted to the barcode font. Strange characters may append to the beginning and end of the data from the fields, but this is normal. In some cases, the data may need to be reformatted and may appear scrambled. This is normal for Code 128 and Interleaved 2 of 5 barcode fonts when numbers need to be compressed within the barcode.
- After verifying that the text in the cell has been formatted correctly, select the appropriate font and set the point size to 12. This example selects the IDAutomationC128XS font. The XS and S sizes of IDAutomation's fonts in Code 128 and Code 39 are specifically designed to format correctly in Excel, as larger fonts will not usually format correctly in the cell. 2D symbols within Excel directly are only possible with the 2D XLS font for Excel.
- Ensure that the column is wide enough to contain the entire barcode with some white space before and after the barcode.
- Scan the printed barcodes with a handheld USB barcode scanner to verify the correct data is encoded.
Symbology Specific Tutorials for Excel:
2D Barcodes:
Basic Vba Excel For Mac
Linear Barcodes:
Barcoding an Entire Column in Excel
IDAutomation's barcode fonts and Macros provide an easy method of barcoding a column in Excel. In this example, Code 128 barcodes are created in Column B from data in Column A. This example assumes the Code 128 Barcode Font Package has been installed, and the VBA module has been imported into the spreadsheet.
- Enter the formula in one cell to format the data to the barcode font as explained in the Barcode Tutorial for Excel:
- Select that cell and choose Edit - Copy.
- At this point, it may be necessary to deselect any cells not needed for barcoding. Then, highlight an entire column by selecting the gray square letter-labeled area at the top of the spreadsheet and choose Edit - Paste. In this example, the button is marked B. If the spreadsheet is large, the formulas may take some time to paste and re-calculate if the spreadsheet is large.
- Change the column to the appropriate barcode font. In this example, choose the IDAutomationC128XS font while the entire column that contains the formula is selected. The barcodes will appear in the entire column. When displaying 2D barcodes in Excel such as QR-Code, Data Matrix or PDF417, use the 2D XLS Font specifically designed for Excel at 8 points.
- Confirm that the barcodes are accurate by scanning them from printed sheets, or directly from the screen. IDAutomation offers a variety of barcode readers that can perform this function with ease.
Video Tutorials
- Video: How to Create a Barcode in Excel
- Video: How to Create a Barcode in Excel 2007 and above
- Video: How to Create a Barcode on Mac Excel 2004
Access VBA Macro Barcode Functions Tutorial
After the appropriate files have been downloaded and extracted, open the sample Access database provided. This database contains one table, one module, and some sample reports. The module contains custom VBA code, functions, and Macros. The sample database should be used as a reference if help is needed.
How to Create Barcodes in an Access Report
Before starting this tutorial, ensure that VBA Macros are the desired implementation. Several methods of creating barcodes in Access are explained in the Barcode Integration Guide for Microsoft Access.
- If a different database is being used and not the sample provided, first import the VBA Macros into the database.
- The most recent versions of Access require a medium security setting to run Macros.
- Open Access and set the security level to medium by choosing Tools - Macro - Security.
- If prompted when the document is reopened, select Enable Macros.
Office 2007 and above may require that the Macros run from a trusted location. Signed Macros are included in the latest version of the VBA download. Simply choose the Trust this Publisher option and the VBA Macros will run unprompted. Tables, Reports, Forms and other information may be pasted into these files and used if the Macros are not modified.
- Open a report in Design Mode.
- Create a text box where the barcode will display.
- To format the data to the desired barcode font in a text box, a function must be placed in the Control Source specifying the data field that needs to be encoded.
- The formula =function([field]) should be entered in the Control Source property of the text box, for example:
- In some cases, it may be necessary to specify the table and field in the control source, for example: If unsure of which function to use, consider the =Code128([field]) function with Code 128 Barcode Fonts.
- Optional: The Control Source may be changed to a formula that appends text to the data or combines multiple fields, for example: or or
- In Code 128, the ApplyTilde feature may also be used to encode tab and return functions. For example, the following formula creates a tab function between two fields:
- Run the report to make sure the data is being populated from the fields and formatted to the barcode font. Strange characters may append to the beginning and end of the data, but this is normal. In some cases, the data may need to be reformatted and it may appear to be scrambled. This is normal for Code 128, Interleaved 2 of 5, DataBar and 2D barcodes.
- Change the formula field font to the appropriate barcode font and set the point size to 12. If this step is not followed, generated barcodes will not display.
- Print and scan the barcodes to verify that the correct data is encoded. If a scanner is needed to verify barcodes, consider the IDAutomation USB Barcode Scanner.
Note: When distributing Access Databases, the associated barcode font must be installed on each computer that prints the barcodes. If this is inconvenient, the Native Barcode Generator for Access is a complete barcode generator object that stays embedded in the database, which means no fonts need to be installed on user computers. For more information about other methods of barcoding in Access, please refer to the Microsoft Access Barcode Integration Guide.
Vba For Mac Excel Spreadsheet
If a large amount of data needs to be encoded, the PDF417 Barcode Font and Encoder or the Data Matrix Barcode Font and Encoder may be the best options as these 2D barcode types allow for the encoding of more data.
Video Tutorial Create a Barcode in Access 2010 and above
VBA & Macro Functions in Microsoft Word Mail-Merge
Before starting this barcode tutorial, ensure VBA Macros are the desired implementation for a Word mail-merge. An easier method exists when using Codabar or Code 39 fonts, and this is explained further in the Barcode Integration Guide for Microsoft Word.
Excel must be used as the data source when creating barcodes in a Microsoft Word mail merge using Macros. The field used for the data source in Word should be the column in Excel where the formula has been applied, which is used to format the data to the barcode font. It is best to use the last column of the spreadsheet in order to avoid merging conflicts.
To set up an Excel spreadsheet with these barcode Macros, refer to the Barcode Tutorial for Excel.
Note: C128 ReturnTypes 6 through 9 are not currently supported in Excel-Word mail-merges.
- Excel 2000 and 2003 require a medium security setting to run Macros. Open Excel and set the security level to medium by choosing Tools - Macro - Security.
Office 2007 and above may require the Macros to run from a trusted location.
In Office 2004 for Mac, go to Excel - Preferences - Security and select Macro Security to enable the secure setting. - After the files have been downloaded and extracted, open the included Word Mail-Merge document. A message may appear stating that the data source cannot be found. If so, select Data Source for Word Mail Merge.xls as the data source. If asked, enable Macros.
- The formula may be viewed in the cells of the Barcode column in the Excel spreadsheet. This formula retrieves the data to encode and passes it to the appropriate barcode function. The function will then format the data to the barcode font. This column is then passed to Word when the mail merge is started. The appropriate barcode font must be selected for the field in MS Word; in this case, it is «Barcode».
- The barcode will not look correct and will not scan until the mail merge is performed.
- After the merge is performed, print and scan the barcode to verify that the correct data has been encoded. If a scanner is needed to verify barcodes, IDAutomation suggests easy-to-use USB Barcode Scanners.
- When distributing the mail-merge, the font should be embedded in Word and the Excel data source must be accessible.
VBA Barcode Macro Functions and Properties
The functions listed below are available in IDAutomation's IDAutomationVBA.bas file and are only valid when used with the font listed in the 'font to use' column. Functions beginning with IDAutomation_Uni_ may only be used with the IDAutomation Universal Barcode Font Advantage™ package and are supplied in the IDAutomationWindowsDLLVBA.bas file provided within that package.
DataToEncode is the string data type for all functions listed below. Other data types such as numbers or dates may need to be converted to the string data type to be properly encoded. Additional parameters are available for some functions and are optional. For example, Code128('123456',0,True). For UPC-A, UPC-E & EAN-13, the +2 and +5 add-on codes may be created by adding the digits to the end of the data being encoded.
VBA Functions for Standard Barcode Fonts | |||
Barcode Type | Barcode Function Methods | Notes | VBA File to Import | Required Font |
Code-11 | Code11 (DataToEncode) | IDAutomationVBA.bas | IDAutomationC11 |
Code-128 (Auto Mode) | Code128 (DataToEncode, C128 ReturnType, ApplyTilde) Human Readable text is enabled when ReturnType = 6 Example: Code128('123456789012', 6, 0) | IDAutomationVBA.bas or IDAutomation VBA for Code 128 and Postnet.bas* | IDAutomationC128 |
Code-128 (Manual Mode) | IDAutomation recommends using Auto Mode for most situations. Code128a (DataToEncode, C128 ReturnType) Code128b (DataToEncode, C128 ReturnType) Code128c (DataToEncode, C128 ReturnType) Example: Code128b('12345678', 6) | IDAutomationVBA.bas or IDAutomation VBA for Code 128 and Postnet.bas* | IDAutomationC128 |
Code-39 | Code39 (DataToEncode) Code39Mod43 (DataToEncode, ReturnType) Example: Code39Mod43('12345678', 0) | IDAutomationVBA.bas | IDAutomationC39 |
Code-93 | Code93 (DataToEncode) | IDAutomationVBA.bas | IDAutomationC93 |
Codabar | Codabar (DataToEncode) | IDAutomationVBA.bas | IDAutomationCB |
EAN-13 | IDAEAN13 (DataToEncode) | IDAutomationVBA.bas | IDAutomationUPCEAN |
EAN-8 | IDAEAN8 (DataToEncode) | IDAutomationVBA.bas | IDAutomationUPCEAN |
GS1-128 | Code128 (DataToEncode, C128 ReturnType, 1) GS1-128 is enabled in Code 128 Auto by setting ApplyTilde to True. Human Readable AIs may be created by setting the C128 ReturnType to 6. Example: Code128('(12)3456789012', 6, 1) | IDAutomationVBA.bas or IDAutomation VBA for Code 128 and Postnet.bas* | IDAutomationC128 |
Interleaved 2 of 5 | I2of5 (DataToEncode) I2of5Mod10 (DataToEncode, ReturnType) Example: I2of5Mod10('123456789', 1) NOTE: ReturnType 3 generates an OPC (Optical Product Code) symbol. OPC is also known as Vision Council of America OPC, VCA BarCode & VCA OPC.Example: I2of5Mod10('020748721', 3) | IDAutomationVBA.bas | IDAutomationI25 |
MSI / Plessey | MSI (DataToEncode, ReturnType) | IDAutomationVBA.bas | IDAutomationMSI |
RM4SCC | RM4SCC (DataToEncode) | IDAutomationVBA.bas | IDAutomationRM |
UPC-A | UPCa (DataToEncode) | IDAutomationVBA.bas | IDAutomationUPCEAN |
UPC-E | UPCe (DataToEncode) | IDAutomationVBA.bas | IDAutomationUPCEAN |
USPS IntelligentMail (IMb) | IntelligentMail (DataToEncode) ** Included only in the purchased version of the USPS IMb Font Package. | IDAutomation VBA for Intelligent Mail.bas | IDAutomationPOSTNET or IDAutomationIMB |
USPS Postnet | Postnet (DataToEncode, ReturnType) *Included in Postnet package. | IDAutomationVBA.bas or IDAutomation VBA for Code 128 and Postnet.bas* | IDAutomationPOSTNET |
USPS Planet | Planet (DataToEncode, ReturnType) | IDAutomationVBA.bas or IDAutomation VBA for Code 128 and Postnet.bas* | IDAutomationPOSTNET |
not applicable | MOD10 (DataToEncode) | IDAutomationVBA.bas | not applicable |
not applicable | SpliceText (DataToEncode, SpacingNumber, ApplyTilde) | IDAutomationVBA.bas | not applicable |
Functions for the Universal Barcode Font | |||
All functions listed below are preceded with IDAutomation_Uni_.* They may only be used with the IDAutomation Universal Barcode Font Advantage™ and are supplied in the IDAutomation_UniversalFont_VBA.bas or the IDAutomationWindowsDLLVBA.bas file which also requires the installation of the product EXE file in order for the macro to function, because they access an installed IDAutomationNativeFontEncoder.dll that is provided within the package. Note: Excel 2004 for Mac requires the functions to be lowercase. Ex: idautomation_uni_c128 | |||
Barcode Type | Universal Function Methods | Notes | VBA File to Import | Required Font |
Code-128 | IDAutomation_Uni_C128 (DataToEncode, ApplyTilde) Note: Code128() is the recommended method to use. Code128() is also used to create GS1-128. IDAutomation_Uni_C128A (DataToEncode) IDAutomation_Uni_C128B (DataToEncode) IDAutomation_Uni_C128C (DataToEncode) Example: IDAutomation_Uni_C128 ('Ê8100712345Ê2112WH5678', TRUE) Excel for Mac: idautomation_uni_c128 ('Ê8100712345Ê2112WH5678', TRUE) | IDAutomation_UniversalFont_VBA.bas or IDautomation_WindowsDLLVBA.bas and IDAutomationNativeFontEncoder.dll | IDAutomation_Uni |
not applicable | C128HR (DataToEncode, ApplyTilde) Returns text for Code 128 barcodes, such as for GS1-128. | IDAutomation_UniversalFont_VBA.bas or IDautomation_WindowsDLLVBA.bas and IDAutomationNativeFontEncoder.dll | Text Font |
Code-39 | IDAutomation_Uni_C39 (DataToEncode, N_Dimension, IncludeCheckDigit) Example: IDAutomation_Uni_C39 ('123456789', 3, TRUE ) Excel for Mac: idautomation_uni_c39 ('123456789', 3, TRUE ) | IDAutomation_UniversalFont_VBA.bas or IDautomation_WindowsDLLVBA.bas and IDAutomationNativeFontEncoder.dll | IDAutomation_Uni |
Codabar | IDAutomation_Uni_Codabar (DataToEncode, N_Dimension, StartChar, StopChar) Example: IDAutomation_Uni_Codabar ('123456789', 3,'A','B' ) Excel for Mac: idautomation_uni_codabar ('123456789', 3,'A','B' ) | IDAutomation_UniversalFont_VBA.bas or IDautomation_WindowsDLLVBA.bas and IDAutomationNativeFontEncoder.dll | IDAutomation_Uni |
Interleaved 2 of 5 | IDAutomation_Uni_I2of5 (DataToEncode, N_Dimension, IncludeCheckDigit) | IDAutomation_UniversalFont_VBA.bas or IDautomation_WindowsDLLVBA.bas and IDAutomationNativeFontEncoder.dll | IDAutomation_Uni |
MSI / Plessey | IDAutomation_Uni_MSI (DataToEncode, N_Dimension, IncludeCheckDigit) | IDAutomation_UniversalFont_VBA.bas or IDautomation_WindowsDLLVBA.bas and IDAutomationNativeFontEncoder.dll | IDAutomation_Uni |
USPS IntelligentMail | IDAutomation_Uni_IntelligentMail (DataToEncode) ** | IDAutomation_UniversalFont_USPS_IMb_VBA.bas | IDAutomation_Uni |
USPS Postnet | IDAutomation_Uni_Postnet (DataToEncode, IncludeCheckDigit) | IDAutomation_UniversalFont_VBA.bas or IDautomation_WindowsDLLVBA.bas and IDAutomationNativeFontEncoder.dll | IDAutomation_Uni |
USPS Planet | IDAutomation_Uni_Planet (DataToEncode, IncludeCheckDigit) | IDAutomation_UniversalFont_VBA.bas or IDautomation_WindowsDLLVBA.bas and IDAutomationNativeFontEncoder.dll | IDAutomation_Uni |
Functions for the DataBar Barcode Font | |||
The functions listed below are preceded with IDAutomation_GS1 and are only provided with the IDAutomation DataBar Font Advantage Package. | |||
Barcode Type | DataBar Barcode Function Methods | Notes | VBA File to Import | Required Font |
DataBar | DataBar (DataToEncode) | IDAutomationGS1DataBar.bas | IDAutomation DataBar 34 |
DataBar Expanded | DataBarExpanded (DataToEncode, 22) | IDAutomationGS1DataBar.bas | IDAutomation DataBar 34 |
DataBar Exp. Stacked | DataBarExpanded (DataToEncode, Segments) | IDAutomationGS1DataBar.bas | IDAutomation DataBar 34 |
DataBar Stacked Omnidirectional | DataBarStacked (DataToEncode) | IDAutomationGS1DataBar.bas | IDAutomation DataBar 34 |
The functions listed below are rare and not approved for POS systems. | |||
DataBar Limited | DataBarLimited (DataToEncode) (Not approved for POS) | IDAutomationNativeWindowsDLLVBA.bas and IDAutomationNativeFontEncoder.dll | IDAutomation DataBar 13 |
DataBar Stacked | DataBarStacked (DataToEncode) (Not approved for POS) | IDAutomationNativeWindowsDLLVBA.bas and IDAutomationNativeFontEncoder.dll | IDAutomation DataBar 13 |
DataBar Truncated | DataBar (DataToEncode) (Not approved for POS) | IDAutomationNativeWindowsDLLVBA.bas and IDAutomationNativeFontEncoder.dll | IDAutomation DataBar 13 |
2D Font Functions | |||
Regarding all symbologies listed in this section below:
| |||
Barcode Type | 2D Function Methods | Notes | VBA File to Import | Required Font |
Data Matrix | IDAutomation_DMatrix_FontEncoder(DataToEncode As String, Optional ProcessTilde, Optional EncodingMode, Optional PreferredFormat) Complete VBA is only provided in the purchased version. | IDAutomation_DM_FontEncoder.bas (2020 Release) | IDAutomation2D or IDAutomationDMatrix |
EncDM(DataToEncode As String, Optional ProcessTilde, Optional EncodingMode, Optional PreferredFormat) | IDAutomation_Datamatrix_ActiveX_Macro.bas and IDAutomationDMatrix.dll (Legacy ActiveX Version) | ||
QR-Code | IDAutomation_QRFontEncoder(DataToEncode) All parameters are set to default except ApplyTilde which is set to 1. | IDAutomation_VBA_QRCode_FE2021 (2021 Release) | IDAutomation2D |
PDF417 | IDAutomation_PDF417(DataToEncode As String, Optional EccLevel As Integer, Optional ColumnSpecify As Integer, Optional RowSpecify As Integer, Optional Truncate As Integer, Optional ForceBinary As Integer) As String | IDAutomation_Native_PDF417_Macro.bas | IDAutomation2D or IDAutomationPDF417 |
IDAutomation_PDF417(DataToEncode As String, Optional EcLevel As Integer, Optional TotalColumns As Integer, Optional TotalRows As Integer, Optional Truncated As Integer, Optional PDFMode As Integer, Optional ApplyTilde As Integer) As String | IDAutomation_PDF417_Macro.bas and IDAutomationPDF417.dll (Legacy ActiveX Version) | ||
Aztec | EncAztec(DataToEncode As String, Optional ProcessTilde, Optional Error Correction) | IDAutomation_Aztec_Macro.bas and IDAutomationAztec.dll | IDAutomation2D |
Maxicode | EncMC(DataToEncode as String, Optional EncodingMode as Int) The default Encoding Mode is 2 | IDAutomation_MaxiCode_Macros.bas | IDAutomation Maxicode |
Barcode Function Descriptions
- ApplyTilde: If set to '1' or 'True', characters following the tilde may be used to perform additional calculations or encode ASCII characters directly.
- DataToEncode: This string value represents the data being encoded.
- N_Dimension: Determines the width of the wide bars when applicable, which is a multiple of the X dimension. Valid values are 2, 2.5 and 3. The default is 2. The X dimension is determined by the font point size.
- IncludeCheckDigit: A Boolean value that determines whether a check digit should be automatically calculated and included for the DataToEncode.
- Segments: Reducing segments to a low, even number such as 4, 6 or 8 in a DataBar Expanded symbol can create a stacked barcode. The default is 22.
Mac Excel Macros
** The USPS Intelligent Mail (IMb) function is supplied in pure VBA code with the purchased version of the associated font package.