Ameba Ownd

アプリで簡単、無料ホームページ作成

cauvaswombphe1972's Ownd

Introduction to vba programming pdf

2022.01.16 00:39




















Introduction to VBA for Excel. Author : Steven C. The handling of numbers in arithmetic and the progression into the more abstract field of mathematics and statistics is generally approached poorly in our education system. The inadequacy is not necessarily in the teaching techniques or the books and other text used but rather in the attitude towards these subjects.


Energy costs impact the profitability of virtually all industrial processes. Stressing how plants use power, and how that power is actually generated, this book provides a clear and simple way to understand the energy usage in various processes, as well as methods for optimizing these processes using practical hands-on simulations. 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. When you open a. 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.


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. 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.


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. 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? Be aware that Application object is implied in all VBA macros. The code that you recorded works with Application.


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. 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. 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! You just combined macro recording, reading the object model documentation, and simple programming to make a VBA program that does something. 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.


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. 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!


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.


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.


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.


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. 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.


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. 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. Although this article is short and only scratches the surface of VBA and programming, it is hopefully enough to get you started. 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. You then set its value and use it to set other variables or properties. 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! 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.