Sei sulla pagina 1di 24

STEP BY STEP

Basic VBA for Excel (macros) in 10 Lessons


Table of Contents Excel Macros : Introduction ....................................................................................... 1 Excel Macros : VBA Vocabulary ............................................................................... 3 Excel Macro Recorder ................................................................................................ 5 VBA for Excel : Visual Basic Editor .......................................................................... 8 Excel Macros : Testing your Code ......................................................................... 12 Excel Macros : Creating a new one ....................................................................... 14 Excel Macros : Testing your VBA Code ................................................................ 15 VBA Excel Macros: Events ...................................................................................... 16 VBA Excel : Controls ................................................................................................ 17 VBA Excel : userforms.............................................................................................. 19 Excel VBA Security and Protection ........................................................................ 21 VBA for Excel (macros) Code ................................................................................. 22

Excel Macros : Introduction Introduction VBA is "Visual Basic for Application". It is a programming language that allows users to program macros to accomplish complex tasks within an application. With VBA for Excel (Visual Basic for Application) you can develop small procedures (macros) that will make your professional life easier and allow you to do more in less time. But VBA is also a very powerful programming language with which you can develop within Excel real programs that will accomplish in a few minutes very complex tasks. With VBA for Excel you can develop a program that does EXACTLY what you need and nothing else. Anybody can develop simple Excel macros but to become very good with VBA you need to know about the most important function in Excel: SUMPRODUCT and you must also master the database functionalities in Excel. Who are these 10 lessons for? I have designed these lessons for my clients who are Accountants, Productions Planners, Production Supervisors, Sales People, Financial Analysts and other Business Data Analysts. Programmers will also appreciate these lessons but I ask them to bear in mind that the objective of these lessons is not to help people rate 10/10 in programming and 5/10 in business solution design but the other way around. I develop VBA code so that it is easily readable by almost anybody.

Page 1 of 24

http://fimot.org/download

VBA is a programming language for users. It is simple and easy to learn. Anybody can develop simple macros (VBA procedures) and with time and interest you can get to a point where you can develop very complex procedures to accomplish very sophisticated tasks. I have developed such VBA procedures at a cost of over $50,000 for certain clients. In any other programming environment (VB, C++, Delphi, etc..) the cost would have easily reached two or three times this amount. VBA for Excel is like any other language (English, French, Italian) even if you master the language if you have nothing to say learning it is a useless endeavor. You can expect to develop very brilliant applications if you: - know your data well (financial, accounting, sales, marketing, inventory, etc.) - know Excel well (SUMPRODUCT, INDEX/MATCH and other important Excel functions plus the Excel database functionalities). No need to learn about very rarely used functionalities like pivot tables, solver, goal seek, scenarios, group and outline and other specialized tools. If you have more that 10 years of experience in your field of expertise (Accounting, Finance, Production, Engineering, etc..) you may want to learn VBA to become an Excel VBA Developer (the market and the money is very good). You might just want to be able to develop easy and very useful macros for yourself but you might also want to learn about VBA to make sure that the person that you are hiring will not spend time and money developing bells and whistles or re-inventing the wheel. Question him abundantly on your type of data and on Excel. If he doesn't know about the SUMPRODUCT function or the database functionalities in Excel call somebody else. What are these 10 lessons? Please don't skip the first chapter on vocabulary. Some of the things I need to talk to you about later will sound like Martian. If you speak Martian move on else.... Then I introduce you to the macro recorder a unique feature that allows you to create macros while you are doing manually what you will want the macro to do. We then take a look at the Visual Basic Editor (VBE) in the next 4 chapters the most user friendly programming environment on the market. You will then learn about EVENTS that trigger macros (Chapter 7), controls (command buttons) and userforms. You will move to chapter (10) on security and protection and then to the 12 pages on VBA code. Visual Basic and VBA What is VBA?
Page 2 of 24

http://fimot.org/download

VBA is "Visual Basic for Application". It is a programming language that allows users to program macros to accomplish complex tasks within an application. There is VBA for Excel, VBA for Word, VBA for Project, VBA for Access and they all differ substantially from one another. Where does VBA come from? In the '70 a new computer language appeared called Basic (I was there). I used it on advanced calculators (TI 59) and on my COCO64 from Radio Shack. At the time, RAM (memory) and CPU's (the brain of the computer) were very, very small and you were limited in what you could do with the language. Yet, I was a Paymaster at the time and I had programmed a complete payroll (salaries, taxes, benefits) for a 500 employees construction business. With today's computer came Visual Basic. It is still Basic but a lot of elements are pre-programmed making the user's task much simpler. Microsoft adopted the language and introduced it as a component of all its applications. Should I learn VBA or VB? Let's say that VB is for programmers and VBA is for users (or developers). Personally, I took hundreds of hours of training in VB but I do all my work in VBA for Excel. You don't need to learn VB to be good at VBA. I adopted VBA because most of the functions that I needed to organize and analyze business data are pre-programmed in Excel. It costs a lot less to develop financial and management applications in Excel than to re-invent the wheel and do everything in VB. What is the difference between VB, VBA for Excel, for Access, for Word, for Project, etc? To answer this question I will ask you to imagine a meeting of five English speaking persons, a Lawyer, an Accountant, a Physician, a Chemist and a Psychologist. They all speak English but when it is time to talk about their work none of them totally understand the other. It is the same with VB and VBA's. The objects, properties and methods vary substantially from one sublanguage to the other. But basically if you speak English you can speak VB or any VBA's.

Excel Macros : VBA Vocabulary Lesson 1: VBA macros Vocabulary In the universe of VBA for Excel (Macros) there is some vocabulary that you might want to adopt so that others can understand you and so that you can understand the others. Excel Macros: Short for macro commands. A series of instructions performed by Excel rather than you.
Page 3 of 24

http://fimot.org/download

VBA Procedure: A set of instructions that you want the computer to execute. In the old days when computers were small and slow and VBA was not well developed these instructions were called Excel MACROS. Code: When you are writing instructions in VBA it is said that your are coding or writing code. Show me your code and I'll show you mine. To write VBA code you will be using 5 types of components: objects, properties, methods, functions and statements Objects: They are the building blocks of your Excel projects they are the application (Excel), the workbooks, the worksheets, the cells and the ranges, the charts, the drawings, the controls (command buttons, text boxes, list boxes, etc.). Properties: Think of the verb to be. All objects have properties that you can set and modify. The font can be bold, the sheet can be visible or not, a workbook has a name, a cell can have a value or a formula, etc. The set of properties differ from one object to the other. A worksheet cannot be bold and a workbook cannot have a formula. Excel will tell you when you are trying to use a property that doesn't exist for the object that you are working with. Methods: Think of the verb to do. You might want an object to close, to open, to be copied or pasted, etc. Again Excel will tell you when you are trying to use a method that doesn't apply to the object that you are working with. Functions: You can and you will use all the Excel functions within your VBA code but you can also use VBA functions like VBA functions like UCASE, LCASE, NOW(), etc... Statements: IF..THEN, DO...LOOP, FOR...NEXT, WITH...END WITH, EXIT FOR, EXIT DO, EXIT SUB For a procedure to start and be executed an event must happen. Events: One event that everybody knows about is the click on the button. Other events include opening a workbook, activating a sheet, modifying the value of a cell, etc... . A VBA project can comprise 4 types of components: a workbook, worksheets, modules, userforms Workbooks: A workbook is an Excel file (something.xls) also called spreadsheet. The object "ThisWorkbook" is the workbook within which the macro is created. Worksheets: An Excel workbook can comprise 256 worksheets each having 65,536 rows and 256 columns.

Page 4 of 24

http://fimot.org/download

Modules: It is kind of file in which you store your macros (VBA procedures). Modules are created and named in the Visual Basic Editor. UserForms: They are specialized sheets that you create to allow the user to submit parameters (values). They are used extensively when working with VB but not with VBA for Excel, they are also used extensively in databases, accounting, manufacturing and sales programs because there are no regular sheets in these environments. When you work with Excel it is so much easier to ask you users to submit parameters on a regular worksheet that forms are not used very much. And then a final word Controls: They are the command buttons, the check boxes, the labels, the text boxes, the list boxes, the option buttons and other gizmos that you put on worksheets or userforms. Example: Sub proTest () Range("A2").Value= 2 Application.Quit End Sub These four lines constitute a procedure (macro) named "proTest". I always name my macros starting with the prefix "pro" and a first capital letter for any significant word comprised in the name like proInfo, proRawData, proWhatever. You will see later how important becomes this prefix and capital letter habit. always start the name of my macros by the prefix "pro". "Range("A2")" and "Application" are objects, "Value" is a property and "Quit" is a method. This VBA procedure will be assigned to a button (control) somewhere and when a user clicks on it (the event) the VBA procedure will run. This VBA procedure tells the computer that when the user clicks on the button, cell "A2" takes a value of 2 and Excel is closed.

Excel Macro Recorder Lesson 2: The Macro Recorder With the Excel macro recorder you cannot develop a macro that will damage Excel or your computer. The bolder you are in your trials the more you will learn.

Page 5 of 24

http://fimot.org/download

I have been developing macros for more than 10 years now and I use the Excel macro recorder daily. Not to learn anymore but to write code for me. The Excel macro recorder is the best teacher that you can have and will remain the best assistant for the rest of your life. Personally, I use the Excel macro recorder a lot to avoid writing code and make spelling errors. I adapt the code that is offered by VBE. Print this page and follow the instructions step by step. First make sure that the macros are nor deactivated in Excel. Go to the menu bar "Tools/Macro/Security". Check "Medium". Close Excel without saving the active workbook and re-open it. From now on every time you open a spreadsheet that contains macros you will be asked to "Enable" or "Disable" the macros. If you choose "Disable" you can open the spreadsheet but the macros won't work. If you don't know who is sending the spreadsheet select "Disable". 1- Open Excel. 2- On the menu bar go to "Tools/Macro/Record New macro" In the following window you see that a macro called "Macro1" will be created. You can change the name if you want. In "Store macro in:" select "This Workbook". When you click on "OK" Excel will record a macro named as you specified and save it in the workbook that you are working in. The macro can run in any workbook but only if this workbook is open. The macro will be saved with this workbook when you save and close it. It also means that Macro1 will die when you delete the workbook. When you go to the Visual Basic Editor (next lesson) you will also see that "Macro1" is stored in "Module1".

3- Click on "OK". A small icon might appear in the middle of the screen, forget about it. 4- Let's now record a macro with the Excel macro recorder:
Page 6 of 24

http://fimot.org/download

Select cell A1 and enter 34 Select cell A2 and enter 55 Select cell A3 and enter the formula =A1 + A2 Select cell A2 and change the color of the font to red Select cell A1 and change the background color to blue Select cell A3 and change the size of the font to 24 5- Go to the menu bar "Tools/Macro/Stop Recording"

Page 7 of 24

http://fimot.org/download

The macro has been recorded by the Excel macro recorder now let's test it 6- Go to Sheet2 7- Go to the menu bar "Tools/Macro/Macros..." select "Macro1" in the list and click on "Run". The macro is executed. 8- Save your workbook as "VBATest1" for the next lesson. You have done it, you have recorded your first macro with the Excel macro recorder and used it, congratulations. Move to lesson 2 and you will be able to look at the macro that you have recorded and then create your own macros.

VBA for Excel : Visual Basic Editor Lesson 3: The Visual Basic Editor You develop VBA procedures (macros) in the Visual Basic Editor (VBE). It is a marvelous user friendly development environment. The VBA procedures developed in the VBE become part of the workbook in which they are developed and when the workbook is saved the VBA components (macros, modules, userforms) are saved at the same time. The VBE is integrated into Excel and you can open it from the Excel Menu Bar "Tools/Macro/Visual Basic Editor" or click on the icon on the Visual Basic ToolBar in Excel. From the VBE you can go to Excel by clicking on the Excel button at the top/left of your screen . So if the VBA toolbar is visible in Excel (View/Toolbar/VBA) you can navigate from VBE to Excel using the two buttons .

Now open the workbook that you have created in lesson 1 "VBATest1.xls" and open the VBE. The Visual Basic Editor When I work with the VBE, there is always 3 windows that are open. The VBAProject window (1), the Property window (2) and the Code window (3). On the menu bar of the VBE choose "View" and select "Project Explorer" then go back to the menu bar and select "Properties Window". You don't call the Procedure window from the menu bar, it is there and contains the VBA code for the element that you have chosen in the "VBAProject"
Page 8 of 24

http://fimot.org/download

window by double clicking on it (sheet, module, form). You can resize the windows by placing the cursor over the borders (*) and drag them right, left, up or down. The VBAProject Window The VBAProject window shows you all the workbooks that are open. You can add forms and modules to any workbook by right clicking anywhere within one of the workbook and select "Insert" in the contextual menu. On your screen you might not see the "PERSONAL.XLS" workbook. It is where I store all my important macros so that I have access to them whenever I open Excel. To learn about creating your own see the offer below. IF you click on the + sign besides "VBAProject(VBATest1,xls) you see that your "VBATest1.xls" has three sheets and one module plus the "ThisWorkbook" object. If you double click on any of the elements the code window will show you the code developed within this element. The properties window will show you the properties of the element that you have selected in the project window. To go on with the lesson double click on Sheet1. If you have more than one workbook open you can copy a module from one workbook to the other by simply left clicking, holding and dragging. The Properties Window (Sheet1) The Properties window shows you the properties of the element that is selected in the VBAProject Window. Double click on "Sheet1" in the project window and the properties windows on your screen will look as the one on the left. You can modify any of the properties from there. The list of properties changes as you select different types of components (thisWorkbook, worksheets, modules, forms or controls). Note that there are two "Name" properties with and without parenthesis. The name
Page 9 of 24

http://fimot.org/download

property "(Name)" on the first line is the programmatical name of the sheet. The other name property "Name" on the9th line is the caption the name of the sheet that the user sees and that you use in your Excel formula. You can either change it here or in Excel. Do the following changes and see what happens in the VBAProject window. Change the name on the 9th line to "Info" and go to Excel to see that the caption of the sheet has changed. Change it back to "Sheet1". Now change the name on the first line to "shInfo" and see in Excel that the caption has not changed. Change it back to Sheet1. On line one give a significant name to your sheets starting with the prefix "sh" and a first capital letter for any significant word comprised in the name like shInfo, shRawData, shWhatever. You will see later how important becomes this prefix and capital letter habit. As far as sheets are concerned I rarely use any other properties than the 2 names. You can make sheets visible or not directly in Excel "Format/Sheet/Hide or Unhide" and when you come back to VBE you will see that the property has changed.

The Properties Window (Module1) Double click on Module1 in the VBAPRoject window and your property window will look like this one. There is only one property, the name. Please, please, please name your modules. So often people send me workbooks for review and all I see is Module1, Module2, Module3.... It is so much friendlier to see modImport, modDatabase, modExportData, modWhatever. Give a significant name to your module starting with the prefix "mod "and a first capital letter for any significant word comprised in the name. You will see later how important becomes this prefix and capital letter habit.

The Code Window In the VBAProject window double click on Module1 and the Code window above will appear. In this code window you can see the procedure that you have recorded called "Macro1".

Page 10 of 24

http://fimot.org/download

Below "End Sub" enter "Sub Macro2()" and click enter. VBE will add a line "End Sub". Now go to the list box (top/right of the Code window) and click on the arrow. You see that you can navigate from one procedure to the other by selecting them in this list. Erase what you have just added (Macro2) and see that it has also disappeared from the list box.

I rarely develop procedures that are triggered by an event related to the worksheet or the workbook. But let's take a quick look at the topic. In the VBAProject window double click on Sheet1. The code window is now empty because you have not developed procedures that are triggered by an event related to the sheet (activate, deactivate, etc...). In the top/left list box (General) select "Worksheet". Automatically VBE creates a procedure called "Worksheet_SelectionChange(ByVal Target As Range)". This automatism annoys me but what can't I forgive Excel. Now if you go to the top/right list box you can see all the events relating to the sheet. Select "Activate". VBE creates a procedure called "Sub Worksheet_Activate()". Here you could develop the procedure so that something happens when you activate the sheet. Erase everything in the code window. In the VBAProject window double click on "ThisWorkbook". The code window is now empty because you have not developed procedures that are triggered by an event related to the workbook (Open, BeforeClose, etc...). In the top/left list box (General) select "Workbook". Automatically VBE creates a procedure called "Workbook_Open()". Now if you go to the top/right list box you can see all the events relating to the workbook. Within the "Workbook_Open()" you
Page 11 of 24

http://fimot.org/download

could develop a procedure so that something happens when you open the workbook. Erase everything in the code window. In the next chapters we will see how to create, test and modify a procedure. Excel Macros : Testing your Code Lesson 4: Modifying Macros Modifying a Macro Let's begin this chapter my modifying the VBA procedure that you have created with the recorder earlier. Open Excel, open the workbook "VBATest1.xls" and go to the Visual Basic Editor. Double click on Module1 in the VBA project window and the following code will appear in the Code window. Click in the code window and print the module for future refernece "File/Print/Current Module" The Macro Recorder (MR) has a very special way to write code. The procedure above works so we could leave it alone but just to make it clearer let's make it simpler. You can replace each line of code yourself or copy/paste the entire new procedure below from this web page onto the old procedure in the VBE When I started the Macro Recorder cell A1 was selected and I entered 34 in it. The MR writes ActiveCell.FormulaR1C1="34" I never use and you will never use the FormulaR1C1 property. Secondly we will add a line of code to tell Excel to start this procedure in cell A1 otherwise, 34 will be entered in the cell that is selected when we start the procedureCell A1 is the ActiveCell and you can replace this line simply by: Range("A1").Select ActiveCell.Value=34 Line 2 and 3 of the procedure read like this: Range("A2").Select ActiveCell.FormulaR1C1 = "55" Again we will avoid the FormulaR1C1 thing and we wont select the cell we will just give it a value so replace lines 2 and 3 by this: Range("A2").Value=55 Line 4 and 5 of the procedure read like this: Range("A3").Select ActiveCell.FormulaR1C1 = "=R[-2]C+R[-1]C" Again we will avoid the FormulaR1C1 but we will not use Value because we want to enter a formula in this cell. Again we wont select the cell we will just

Page 12 of 24

http://fimot.org/download

enter a formula so replace lines 4 and 5 by this: Range("A3").Formula="=A1+A2" Line 6 and 7 of the procedure read like this: Range("A2").Select Selection.Font.ColorIndex = 3 Here we wont select the cell we will just specify that we want to change the color of the font so replace lines 6 and 7 by this: Range("A2").Font.ColorIndex = 3 Three is red. I always use the MR in these situation because I don't feel like remembering all the color codes. Line 8 to 12 of the procedure read like this: Range("A1").Select With Selection.Interior .ColorIndex = 41 .Pattern = xlSolid End With The MR uses a lot of "With..End With" but I don't. The code developed by the MR would read in plain English: Select cell A1 (cell A1 becoming the Selection) then for the Selection.Interior make the ColorIndex be 41 and the Pattern be xlSolid. Here is a simpler version so replace lines 8 to 12 by this: Range("A1").Interior.ColorIndex = 41 Range("A1").Interior.Pattern = xlSolid Line 13 to 25 of the procedure read like this: Range("A3").Select With Selection.Font .Name = "Arial" .Size = 24 .Strikethrough = False .Superscript = False .Subscript = False .OutlineFont = False .Shadow = False .Underline = xlUnderlineStyleNone .ColorIndex = xlAutomatic End With Again MR uses "With...End With" and also modifies ALL the properties of the font each time. We just want the font's size to be changed to 24 so replace lines 13 to 25 by this: Range("A3").Font.Size= 24 The VBA procedure or macro called "Macro1" now looks like this: Sub Macro1() ' Macro1 Macro ' Macro recorded 5/27/2005 by Peter'
Page 13 of 24

http://fimot.org/download

ActiveCell.Value = 34 Range("A2").Value = 55 Range("A3").Formula = "=A1+A2" Range("A2").Font.ColorIndex = 3 Range("A1").Interior.ColorIndex = 41 Range("A1").Interior.Pattern = xlSolid Range("A3").Font.Size = 24 End Sub We will test it in chapter 6

Excel Macros : Creating a new one Lesson 5: Creating Macros with VBA for Excel Let's now create a brand new macro. Open Excel, open the workbook "VBATest1.xls" that you have created in the previous chapter. Add a sheet to your workbook and rename it "Test2" (right click on the tab, chose "Rename" and type the name in). In cell A1 to A10 enter 10 first names and in cells B1 to B10 enter 10 last names. Now let's create a new module. Go to the VBE and right click in the VBA project Window within the project "VBATest1" and select "Insert/Module". You now have a new module. In the properties window double click on the "(Name)" property box and enter "modTest". We now have a new module with a name. In the VBAProject window double click on the sheet named "Test2". In the properties window double click on the "(Name)" property box and enter "shTest2". You now have a sheet with a caption reading "Test2" and with the name "shTest2". In the VBAProject window double click on "modTest2"" and let's go to the code window to develop a macro. Write "Sub proTest2 ()" and click "Enter". VBE adds a line "End Sub". We will write our code between these two lines so make some room for it by setting the cursor at the end of "End Sub" and clicking "Enter" a few times. Just below "Sub proTest2()" write your name preceded by an apostrophe (') ' Peter Clark and click "Enter". Notice that the font in the line you have just written is green. Because of the apostrophe VBA will consider the text as a remark (REM) and will not bother with it. You can add any number of REM lines anywhere to make your code understandable. I usually always start my procedures with three Rem lines (my name, my phone number and the address of my website) so that people can get in touch with me if they experience problems with my VBA procedures.
Page 14 of 24

http://fimot.org/download

Click "Enter" again to insert an empty line. Do not hesitate to insert empty lines anywhere to make your code more easily readable. Here are the 6 lines of code that you will be writing (or copy/paste them from this webpage): shTest2.Select Range("C1").Select Do Until Selection.Offset(0, -2).Value = "" Selection.Value = Selection.Offset(0, -2).Value & " " & Selection.Offset(0, -1) Selection.Offset(1, 0).Select Loop Range("A1").Select The fist 2 lines tell VBA where to start the procedure. If you don't mention it VBA will start the procedure from whatever cell is selected in your workbook. Line 5 to 7 is the actual task that you want VBA to perform. You are saying: do something until the value of the cells 2 columns left of the selected cell in empty (double double quotes). When a cell is selected after the line where is the last first name the task will end. If there is a first name you do else you loop (last line of the statement). What is the task: make the value of the selected cell equal to the value of the cell 2 columns left and (&) a space (space between two double quotes) (" ") and the value of the cell 1 column left of the selected cell. Then move down one cell. When the task has been accomplished go to cell A1. Now go back to Excel go to "Tools/Macro/Macros" select the macro "proTest2" and click "Run". Erase column C and do it again. Add first names and last names to your list and do it again. Congratulations you have created your first VBA procedure. We will test it step by step in the next chapter.

Excel Macros : Testing your VBA Code Lesson 6: Testing Macros Here is a very interesting way to test a macro step by step while seeing it at work in the Excel workbook.
Page 15 of 24

http://fimot.org/download

Close every program on your computer. Open Excel and the workbook "VBATest1.xls" in which we have created a new macro called "proTest2". Open the VBE. On the Window status bar at the bottom of your screen you can see that Excel is open and the VBE also. Right click on the status bar in the empty space. Click on "Tile Windows Vertically" and the screen will look like this:

The Excel workbook occupies half of the screen and the VBE occupies the other half. Make the Code window wider in the VBE so that you can see all the code. Make sure to remove values and formats in cell C1 to C10 of the workbook. In the Excel workbook select cell D3 of the sheet "Test2", and then select any sheet other than "Test2". In VBE, click anywhere within the procedure "proTest2". Click on the F8 key at the top of your keyboard and see that the first line of code become yellow. Click again on F8 and the sheet "Test2" is selected, click again and cell C1 is selected click a few more times until no line in the code is yellow. You have tested your code step by step.

VBA Excel Macros: Events Lesson 7: The Events The event is what triggers the VBA Excel macro. Most macros are activated by clicking on a button. From a workbook in Excel you can run an Excel VBA macro that resides in any of the opened workbooks by going to "Tool/Macro/Macros.." then select the macro and click "Run". This means that you can store ALL your useful
Page 16 of 24

http://fimot.org/download

Excel macros in a single workbook (call it myMacros.xls) and have access to them while the workbook is opened. Let's say for example that you have designed a macro that multiplies the content of a cell by 2. If myMacros.xls is open you can call this Excel macro from any cell in any other workbook that is open. No need to copy your essential macros in all your workbooks just open myMacros.xls and put them to work. You can run these Excel macros in myMacros.xls from a key on your keyboard. To do so go to "Tool/Macro/Macros.." then select the macro. Click on "Options" and follow the instructions. A suggestion, assign your macros to upper case keys ("Shift/A" for example) to make sure that you don't use one of the many lower case keys that are already used by Excel. You can trigger a VBA macro by clicking on a VBA command button on a worksheet. I use VBA command buttons on user forms but never on a worksheets I prefer using text boxes they are much easier to maintain and allow much more creativity design wise. From the "Drawing" toolbar click on the text box icon go to the sheet and stretch one. When the text box border is a set of slashes you are in text maintenance mode click on the border again and it becomes a set of dots you are now in text box maintenance mode. Right click on the border and select "Assign Macro" select an Excel macro that you have already developed and click "OK". From now on when somebody clicks on the text box the Excel macro that you have chosen runs. You can assign a VBA macro to a text box and also to a WordArt, a picture, a chart or any other shape from the "Drawing" toolbar. You can also assign a macro to a new icon that you add to a toolbar or a new menu item. 99% of the Excel macros that I have developed are triggered by a click on a text box located on a worksheet (see how in lesson 8). Other events that can be used to trigger procedures are the opening of the workbook, the activation of a worksheet or the modification of the value of one or more cells. On a user form there are events related to the form, command buttons and other controls.

VBA Excel : Controls Lesson 8: Controls Command buttons In the Chapter on EVENTS (7) I have told you that 99% of my VBA procedures are triggered by a click on a button. And to make things simple I do not use VBA command buttons they are uselessly complicated and limited in how you can shape them.

Page 17 of 24

http://fimot.org/download

No VBA, I work in Excel with text boxes most of the time but also with images and WordArt. Download one of these buttons (right click on it in your browser and choose "Save image as"). Save it on your desktop:

Now open the workbook that you have created "VBATest1.xls" and select the sheet "Test2". Insert the image that you have imported anywhere "Insert/Picture/From File/Desktop/..........gif". Once the image has been added to the sheet, right click on the image and select "Assign Macro and select the macro "proTest2" that you have created earlier. Erase all the values in column C or the sheet and click on the button. So you can "borrow" all kinds of buttons from the Internet or create your own and use them as triggers for your VBA procedures. Once a button (image, word art or text box) has been assigned a macro or an hyperlink you need to select it with a right click to modify it. Most of the time I use text boxes that I create in Excel from the drawing toolbar (the first 4 buttons above). I can use the font that I like and the background color that fits my needs. If you are a little creative you can add 3D effects, special borders and the likes. A few note on Excel text boxes: I always keep the drawing toolbar at the bottom of my screen

You create text boxes by a left click on the icon , you then go to the worksheet and you left click hold and stretch the text box. When the border of the active text box is made of diagonal lines you can work the text. If you click again on the border it becomes a set of dots and you can work the text box itself. Right click on the border in any of the two states and you will see that the menus are different. It is in the second state that you can assign a macro to the text box.

Drop-Down Lists Here again I stay away from VBA and develop my drop-down lists in Excel. If you need drop-down lists in 50 cells to help users select values you need to create 50 drop-down lists one by one. If you use the drop-down list

Page 18 of 24

http://fimot.org/download

functionality in Excel you create one in the first cell and copy/paste it in the other 49 cells. See how to do it on the page on Excel drop-down lists. VBA Command Buttons If you insist on using VBA command buttons here is how you create and maintain them. First activate the VBA toolbar "View/Toolbar/VBA" (I always keep the VBA toolbar visible). . Then click on the toolbox icon use. Here is the toolbox: to see the controls that you can

Left click on the command button, move to the sheet, left click, hold and stretch. Right click on the command button and chose "Properties". Set the properties. Right click again and select "View Code". Write the code. Finally, click on the design icon on the VBA tool bar to activate the command button and close the toolbox. To modify the command button you need to right click on it then click on the design icon on the VBA toolbar and call the properties or code window. The main reason for which I never use VBA command buttons is that you cannot test code step by step within a command button but you can do it in a regular macro in a module, the macro that is assigned to an image a wordart or an Excel text box.

VBA Excel : userforms Lesson 9: Forms and Controls I develop many userforms when I am working with Microsoft Access because it's the only way to ask a user to enter data in the database or to submit whatever parameter to execute a macro. In Excel people can enter data directly on the sheets and they can also submit parameters in cells. Command buttons and drop-down lists can easily be added to a worksheet (see lesson 8) so I almost never use the userforms in Excel. The form or userForm is also known as a GUI (Graphical User Interface). The form is used to require values, parameters and information from the user to feed the VBA procedure. When the message box and the input box are too limited for this purpose you create a form to which you add controls

Page 19 of 24

http://fimot.org/download

(command buttons, text boxes, list boxes, combo boxes, labels and others), pictures and other objects. As you will see developing a form is a lot of fun but quite an endeavor. There are much simpler ways to collect parameters and information from the users in Excel. In fact I very rarely create userforms and use controls. My users supply me with values and parameters on regular sheets and instead of using command buttons, I use Excel text boxes as command buttons. I also use the very simple Excel drop-down lists when needed. This approach is much simpler than using userforms and controls both in the design phase as in the maintenance phase. Here are some tips anyway. Creating a form in VBA is quite easy. In the VBE (Visual Basic Editor ) you right click on your project in the VBAProject window and select "Insert/UserForm" and here is what happens:

In the Properties window you can change the name of the form, its caption (the name in the blue band at the top) and any of the 34 properties of the form. When you name a form always use the prefix "frm" like in "frmDatabase" and be as descriptive as you can be so that your code will be easier to read. Always use one or more upper case letters in the name. When you write "frmDatabase.Show" in lower case letters Excel will not capitalize any letters letting you know that the name is misspelled. To add controls to the form you left click on whatever control that you want in the Toolbox and then you go to the form you left click and hold and expand the control to the desired size. Once all your controls are on the form you left click on them and in the properties window you can change the properties of the selected control. You can also right click on them and select "Properties". Here is a simple form that I have created to ask the user to submit the name of a city. The form's name is "frmCity" and its caption is "City". I have added 4 controls on it a label "lblCity" which caption is "Select a city for the report", a combo box "cbxCity" and two command buttons "cmdCityCancel" and "cmbCitySubmit". I have then resized the form.
Page 20 of 24

http://fimot.org/download

You now need to develop some VBA code to make this form usable. See the chapter on coding for userform in the VBA code section of this website. Excel VBA Security and Protection Lesson 10: Security and Protection Sometimes when you send a workbook with macros in it to a colleague and he can't get them to work it is probably because his security setting is at "High". Just tell him how to change it in "Tools/Macros/Security". An Excel file (.xls) cannot be infected by one of these viruses that appear regularly on the Internet but somebody can develop VBA procedures (macros) that can harm your data and your computer seriously. So set the security level of Excel to "Medium" (Tool/Macro/Security) and each time you will be trying to open a workbook that contains macro the following dialog window will appear.

Adopt the same attitude as you have with documents attached to Emails. If you know the origin of the file you may enable the macros if not click on "Disable Macros" and you are fully protected. You can look at the workbook but the VBA procedures (macros) are not operational. You can go to the Visual Basic Editor to take a look at the macros and if they don't look suspicious close the workbook and re-open it enabling the macros. If in any of the modules or other elements of the workbook you see "API Function" it means that the programmer is trying to access your computer through Microsoft Windows THAT IS SUSPICIOUS.

Page 21 of 24

http://fimot.org/download

Protecting the code As an Excel-VBA Developer you might want to protect your code so that nobody else may modify it. In the VBE editor go to "Tools/VBAProject Properties/Protection". Check the box and submit a password. Make sure that you save the password somewhere you will remember because cracking VBA passwords is very expensive. Protecting the Workbook There are many levels of protection that you can set for the workbook. First you might want to forbid anybody from opening the workbook unless they know a password. To do so in Excel go to "File/Save As" and click on "Tools/General Options". Hiding Worksheets In one of your workbook you might want to hide a sheet that contains confidential information (salaries and other parameters). If you just hide the sheet users can unhide it. There is a VBA way to hide a sheet without protecting the entire workbook. To view the sheet one has to go to the Visual Basic Editor and change the property of the sheet. If your code is protected, he also needs the password. So the sheet is very hidden and only you can get to it to modify its content. Select the sheet in the VBAProject window and set the visible property at xlVeryHidden.

VBA for Excel (macros) Code There are thousands of objects, methods, properties, statements and functions that you can use in VBA. You can create your own objects in the form of variables. One can easily get lost and loose hours trying to search for the important things. I have lost the hours and here are a few of the important elements that you should know about. The code in VBA for Excel to generate the following basic message box : Sub proMessage() MsgBox "Your message here" End Sub

Page 22 of 24

http://fimot.org/download

When you don't want to see your screen follow the actions of your VBA procedure, you start and end your code with the following sentences: Application.ScreenUpdating = False Application.ScreenUpdating = True The following Application.Quit line of code closes Excel altogether.

A worksheet has two names the one that appears on its tab (let's call it its caption) and the one it has as VBA object (by default: Sheet1, Sheet2....). So you can activate Sheet1 whose caption is "Balance" with both: Sheets("Balance").Select Sheet1.Select You can extract a worksheet from a workbook and save it as a new workbook with the following code: shBalance.Copy ActiveWorkbook.SaveAs "newBook.xls" The workbook within which your VBA procedure resides is known as "ThisWorkbook" so you can write things like ThisWorkbook.Save or ThisWorkbook.Close and VBA understands that you are working with the workbook in which resides the VBA procedure that is running. To select rows or columns Rows("1").Select Columns("A").Select to remove all the data in the row or column of the activecell ActiveCell.EntireRow.Select ActiveCell.EntireColumn.Select To move 13 rows up and 14 column to the left of a cell you can use either: ActiveCell.Offset(-13, -14).Select Selection.Offset(-13, -14).Select Range("G8").Offset(-13, -14).Select To select all the cells from a cell or the activecell to 10 cells to the right Range("A1", Range("A1").Offset(0, 10)).Select Range(ActiveCell, ActiveCell.Offset(0, 10)).Select When there is only one condition and one action, you will use the simple statement: If Selection.Value > 10 Then Selection.Offset(1,0).Value = 100 End If

Page 23 of 24

http://fimot.org/download

In plain English: if the value of the selected cell is greater than 10 then the value of the cell below is 100 if not do nothing.

Page 24 of 24

http://fimot.org/download

Potrebbero piacerti anche