Você está na página 1de 18

XL-mania@yahoogroups.

com

VBA Excel Code


Table of Contents
Excel Macros : Introduction...........................................................................................1 Excel (VBA) Macros: Cells and Ranges........................................................................2 Excel Macros : Worksheets............................................................................................3 Excel Macros : the Workbook........................................................................................4 Excel Macros : the Application......................................................................................5 VBA Excel Macros: Functions.......................................................................................6 VBA Excel IF Statements and other Statements............................................................8 VBA for Excel (macros) Message Boxes.....................................................................12 Excel VBA Input Box..................................................................................................14 Excel Macros : Variables.............................................................................................15 VBA Excel : Forms and Controls.................................................................................17 Excel Macros : Introduction Write your code in lower case letters. If the spelling is right, VBE will capitalize the necessary letters. If it doesn't, check your spelling. To create code within an event related to the sheet, right click on the sheet's tab and select "View Code". Then select the event from the event window and write your code. Note:Quotes within quotes must be doubled: Selection.Formula= "=Range ("A1").Value & "normal""must be written Selection.Formula = "=Range(""A1"").Value & ""normal""" MsgBox "My name is "Peter""must be written MsgBox "My name is ""Peter""" Name ALL the cells and ranges that you use in your code so that if their addresses change (adding or deleting columns or rows, changing the name of sheets, etc..), your code is not invalidated. Declare all your variables (Dim) at the beginning of the procedure, it will simplify the testing of your code. Always activate the "Option Explicit". Although, you are forced to declare variables, there are many advantages. If you have the wrong spelling for your variable, VBE will tell you. You are always sure that your variables are considered by VBE. You can use Shift/Space to call your variables in a contextual menu and double click them rather then key them in.

Page 1 of 18 peter@excel-vba.com

XL-mania@yahoogroups.com

Excel (VBA) Macros: Cells and Ranges Working with cells Except for when I want to select all the cells of a worksheet I use the "Range" object when I work with cells To select all the cells Cells.Select Selecting a single cell Range("A1").Select Selecting contiguous cells Range("A1:G8").Select Selecting non-contiguous cells Range("A1,B6,D9").Select Range("A1,B6:B10,D9").Select To select rows or columns Rows("1").Select Columns("A").Select or ActiveCell.EntireRow.Select ActiveCell.EntireColumn.Select To select many contiguous rows or columns Columns("A:C").Select Rows("1:5").Select To select many non-contiguous rows and columns NOTE: Use the "Range" object and not Columns or Rows Range("A:A, C:C, E:F").Select Range("1:1,5:6,9:9").Select To move to the first cell in a row: ActiveCell.Offset(0, -ActiveCell.Column + 1).Select To move to the first cell in the column: ActiveCell.Offset( -ActiveCell.Row + 1,0).Select And to move to the top/left cell of the sheet...... Range("A1").Select To move 13 rows down and 14 column to the right of a cell you can use either: ActiveCell.Offset(13, 14).Select Selection.Offset(13, 14).Select Range("G8").Offset(13, 14).Select
Page 2 of 18 peter@excel-vba.com

XL-mania@yahoogroups.com

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 But most of the time you don't know the number of rows and columns that you have in a set of data so the most important property of the Range object, the ActiveCell and the Selection is the CurrentRegion. It includes all the cells until there is an empty column and an empty row. I use it daily when I work with data imported form all kinds of program. For example if there are data from cell A1 to cell K5600 the line Range("A1").CurrentRegion.Select will select all the cells from cell A1 to cell K5600. I can then count the rows and the columns of the current region and easily move from the first to the last column or row. To move to the end of the set of data I will use: Range("A1").Offset(varNbRows, varNbColumns).Select and to position myself to add a new record Range("A1").Offset(varNbRows, 0).Select Most book on VBA for Excel will suggest the following lines of code to go to the lat row or the lat column: Range("A1", Range("A1").End(xlDown)).Select Range(ActiveCell, ActiveCell.End(xlDown)).Select Range("A1", Range("A1").End(xltoRight)).Select Range(ActiveCell, ActiveCell.End(xltoLeft)).Select but if you use these lines of code and there data only in cell A1 you end up in cell A65000 or IV1 and you have a problem. That is why I always select the current region of a set of data and I use the offset property as in the example above. We have use the Offset property to move up and down or left and right a certain number of cells and select the cell that we then reach. 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 To select a range from a cell or the activecell to 10 cells to the left Range("A1", Range("A1").Offset(0, -10)).Select Range(ActiveCell, ActiveCell.Offset(0, -10)).Select To select a range from a cell or the activecell to 10 cells below Range("a1", Range("a1").Offset(10, 0)).Select Range(ActiveCell, ActiveCell.Offset(10, 0)).Select Excel Macros : Worksheets Working with Worksheets

Page 3 of 18 peter@excel-vba.com

XL-mania@yahoogroups.com

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 I prefer the second method for 2 reasons first there is less to key in and secondly if ever you or your user change the caption of the sheet there is no need to review and correct your code accordingly. The only disadvantage is that the VBA code is not clear and easy to read. That is why I rename the sheets in the Visual Basic Editor (I select the sheet in the Project Window and modify the name in the Property Window). In the example below the name of the sheet (as VBA object) is shBalance: shBalance.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" Excel Macros : the Workbook ThisWorkbook ThisWorbook is a VBA-object: it is THE workbook within which the procedure runs. You will use ThisWorkbook.Activate instead of repeating Windows("SOandSO.xls").Activate. If somebody changes the name of the workbook, you don't have to worry. Path When the user opens a workbook through Windows Explorer, the "File Open" procedure of Excel points to the default directory. So, if you want to open a second workbook residing in the same directory within this first workbook, Excel won't find it. To avoid this problem, I ALWAYS create a variable identifying the path of the first workbook at the beginning of the procedure within which I am calling the second workbook: varPath= ThisWorkbook.Path I then use this variable within the OPEN event: Workbooks.Open varPath & "\Workbook2.xls" Saved and Close If you want to close ThisWorkbook without saving it: ThisWorkbook.Saved = True ThisWorkbook.Close

Page 4 of 18 peter@excel-vba.com

XL-mania@yahoogroups.com

Working with Workbooks 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. You can open other workbooks with a VBA procedure. Before we proceed though there is one thing that you should know and that is very important. If manually you open Excel and then with the "File/Open" menu item you select a workbook, the "Open", "Save" and "SaveAs" directories are all three the directory in which resides the workbook that you have just opened. If you open a workbook from Windows Explorer the "Open", "Save" and "SaveAs" directories are all three the default directory of Excel usually "My Documents". So if you write Workbooks.Open "OtherWorkbook.xls" without specifying the path VBA will be looking in either the default directory or the directory of the workbook from which the VBA procedure runs depending if you or your user has opened the first workbook from Excel or from Explorer. To avoid problems you can specify the path like in Workbooks.Open "C:\ \OtherWorkbook.xls". When two workbooks are open and you want to move from one to the other you will use Thisworkbook.Activate and Windows("OtherWorkbook.xls").Activate If you don't want to hard code the name of the workbook that you want to open you can write the name in a cell (cell A1 of the sheet shBalance for example) and write: Workbooks.Open shBalance.Range(A1").Value I prefer to put the name of the workbooks in a variable and then I use the variable all along the procedure. Excel Macros : the Application Application Application is a VBA-object, IT IS EXCEL. Whenever you want Excel to do something or you want to change a property of Excel, you will use the object Application. ScreenUpdating 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

Page 5 of 18 peter@excel-vba.com

XL-mania@yahoogroups.com

CutCopyMode After each Copy/Paste operation, you should empty the clipboard with the following line of code to make sure that the computer memory doesn't overload. ActiveSheet.Paste Application.CutCopyMode=False Quit The following line of code closes Excel altogether. Application.Quit GoTo To select a certain cell you can use Application.Goto Reference:=Range("V300") or more simply Range("V300").Select But if you want this cell to be selected and be the top/left cell on your screen you will use Application.Goto Reference:=Range("V300"), Scroll=True There are other interesting things that you can do with the object APPLICATION. You can interrupt calculations while a procedure is running to make things faster. You then make them manual again at the end and the calculations are executed. If at a certain point during the procedure you still want to execute some or all of the calculations you can tell Excel to calculate a sheet or the entire workbook without changing the status of the calculations. With the APPLICATION object you can also cancel all the messages like "Do you want to save this workbook?", "A file with this name already exist do you want to replace it". See how you can do these things and more with the object APPLICATION in my 35 Excel and VBA Macro Tutorials . VBA Excel Macros: Functions Functions Three topics in this lesson: using Excel functions within macros, creating new Excel functions with VBA for Excel and then using VBA functions within macros. Existing Excel Functions There are hundreds of functions available in VBA. Most of the functions that you find in Excel are available within macros in this form: Range("C1").Value=
Page 6 of 18 peter@excel-vba.com

XL-mania@yahoogroups.com

Application.WorksheetFunction.Sum(Range("A1:A32")) this sentence sums the values of cell A1 to A32 and stores the total in cell C1. New Excel Functions You can create new functions in Excel. For example the function created by the code below will simply multiply the value of a cell by 2. Function fctDouble(varInput) fctDouble = varInput * 2 End Function Once this code is in a module in your workbook you access the new function the same waythat you access to other functions by clicking on the icon function on the tool bar or from the menu bar "Insert/Functions". In the dialog box select the "User Defined" category and select "fctDouble" and follow the instructions. I have created a New Excel function that translates numbers into words like $149.50 into "one hundred forty nine dollars and fifty cents". Tou will find this function in my 35 Excel-VBA tutorials. VBA Functions Here are some VBA functions that I use within my Excel macros: LCase, UCase The IF statements, the SELECT CASE and DO WHILE are all case sensitive. When you test a string of characters and you don't know if the user will enter upper case or lower case letters, use the LCase or USase functions within your test and write the string in proper case: If LCase(Selection.Value)= "toto" then... or Select Case LCase(Selection.Value) or Do While LCase(Selection.Value)<>"toto" If UCase(Selection.Value)= "TOTO" then... or Select Case UCase(Selection.Value) or DO WHILE UCase(Selection.Value)<>"TOTO" NOW() NOW() is an Excel function but also a VBA function. With the following code the Excel formula NOW() is inserted in cell A1. The cell "A1" will show the date of the day and this date will change every time the workbook is opened: Range("A1").Formula = "=Now()"
Page 7 of 18 peter@excel-vba.com

XL-mania@yahoogroups.com

With the following code, the cell "A1" will carry the date when the procedure is executed and will keep this value until you execute the procedure again. It won't change every time you open the workbook. Range("A1").Value = Now() VBA Excel IF Statements and other Statements Statements The statements that I use more often in my VBA Excel macros are: If..Then..End If, Do...Loop, For...Next and Select Case If..Then...End If 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 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. Note: Tests on strings are case sensitive so when you test a string of characters and you don't know if the user will use upper case or lower case letters, use the function LCase function within your test and write the strings in your code in lower case letters: If LCase(Selection.Value).Value= "yes" then... With this approach, your test will be valid whatever case your client uses (Yes, YES or any other combination of cases). If..Then...End If (multiple tiers) When there are only two conditions that you want to check sequentially, you will use the statement: If Selection.Value > 10 Then If Selection.Value = 12 Then Selection.Offset(1,0).Value = 100 End If End If In plain English: first check if the value of the selected cell is greater that 10. If it is not do nothing. If it is check if the value of the selected cell is equal to 12. If so set the value of the cell below at 100 else do nothing. If..Then...And...End If When there are two inclusive conditions, you will use the statement: If Selection.Value >= 10 And Selection.Offset(0,1).Value < 20 Then

Page 8 of 18 peter@excel-vba.com

XL-mania@yahoogroups.com

Selection.Offset(1,0).Value = 100 End If In plain English: if the value of the selected cell is greater or equal to 10 and smaller than 20 the value of the cell below is 100 otherwise do nothing. If..Then...Or...End If When there are two exclusive conditions and one action, you will use the statement: If Selection.Value = 10 Or Selection.Offset(0,1).Value = 20 Then Selection.Offset(1,0).Value = 100 End If In plain English: if the value of the selected cell is equal to 10 or equal to 20 then the value of the cell below is 100 otherwise do nothing. If..Then...Else...End If When there is only one condition but two actions, you will use the statement: If Selection.Value > 10 Then Selection.Offset(1,0).Value = 100 Else Selection.Offset(1,0).Value = 50 End If In plain English: if the value of the selected cell is greater than 10 then the value of the cell below is 100 else the value of the cell below is 50. If..Then..ElseIf...End If When there are more than one condition linking each to a different action you will use the statement: If Selection.Value = 1 Then Selection.Offset(1, 0).Value = 10 ElseIf Selection.Value = 2 Then Selection.Offset(1, 0).Value = 20 ElseIf Selection.Value = 3 Then Selection.Offset(1, 0).Value = 30 ElseIf Selection.Value = 4 Then Selection.Offset(1, 0).Value = 40 ElseIf Selection.Value = 5 Then Selection.Offset(1, 0).Value = 50 End If In plain English: If the value of the selected cell is 1 then the value of the cell below is 10 but if the value of the selected cell is 2 then the value of the cell below is 20 but if the value of the selected cell is 3 then the value of the cell below is 30 but if the value of the selected cell is 4 then the value of the cell below is 40 but if the value of the selected cell is 5 then the value of the cell

Page 9 of 18 peter@excel-vba.com

XL-mania@yahoogroups.com

below is 50 but then if the value of the selected cell is not 1, 2, 3, 4 or 5 do nothing. You can use IF..ElseIf when you have 2 or 3 conditions but if you have more you might want to use the much more interesting Select..Case statement. See my 35 Excel-VBA tutorials for step by step explanations. Do..Loop The Do...Loop statement does pretty much the same thing as the For..Next statement but you don't need to declare a counter because the Loop stops when it encounters a certain condition. Try the following procedure by first entering 1 in cells A1 to A7 or A27 or to as far down as you want to go. Sub proTest() Range("A1").Select Do Until Selection.Value = "" Selection.Value = Selection.Value + 1 Selection.Offset(1, 0).Select Loop End Sub In plain English: starting in cell A1 add 1 to the value of the selected cell and move one cell down. Do this until the value of the selected cell is nothing. Variation on the statement: Do Until Selection.Value = "" Do until the selected cell is empty Do While Selection.Value <> "" Do as long as the selected cell is not empty Loop Until Selection.Value = "" Loop until the selected cell is empty Loop While Selection.Value <>"" Loop as ong as the selected cell is not empty Exit... You may exit a FOR..NEXT, DO...LOOP and even a procedure at any time with the EXIT statement If Selection.Value > 10 Then Exit For

Page 10 of 18 peter@excel-vba.com

XL-mania@yahoogroups.com

If Selection.Value > 10 Then Exit Do If Selection.Value > 10 Then Exit Sub With...End With In the old days when computer memory was rare and expensive and computers were not very powerful programmers would us a lot of With..End With statements ebcause is was less requiring on the memory and the capacities of the computer. When you develop in VBA for Excel (very small programs) memory is not really an object and our personnal computers are as powerful as the large computers of yesterday. The macro recorder uses a lot of With..End With statements but I personnaly don't. Anyway here how it works. Range("A3").Select Selection.Font .Name = "Arial" .Size = 24 .Strikethrough = False .Superscript = False .Subscript = False .OutlineFont = False .Shadow = False .Underline = xlUnderlineStyleNone .ColorIndex = xlAutomatic End With is the same as writing Range("A3").Select Selection.Font.Name = "Arial" Selection.Font.Size = 24 Selection.Font.Strikethrough = False Selection.Font.Superscript = False Selection.Font.Subscript = False Selection.Font.OutlineFont = False Selection.Font.Shadow = False Selection.Font.Underline = xlUnderlineStyleNone Selection.Font.ColorIndex = xlAutomatic Both work it's your choice. For..Next The FOR...NEXT loop is the one I use the most. It allows you to repeat an action a certain number of times.

Page 11 of 18 peter@excel-vba.com

XL-mania@yahoogroups.com

Sub proTest() Range("A1") = 10 Range("A2").Select For varCounter = 1 To 10 Selection.Value = Selection.Offset(-1, 0).Value * 2 Selection.Offset(1, 0).Select Next End Sub In plain English: Set the value of cell A1 to 10 then select cell A2. While the counter is going from 1 to 10 (10 times in other words) the value of the selected cell is twice the value of the cell above...move one cell down. Resulting from this procedure, Cell A1=10, A2=20, A3=40.....A11=10,240. If you'd write: For varCounter = 1 To 10 Step 2 the deed would be performed only 5 times. Resulting from this procedure, cell A1=10, A2=20, A3=40.....A6=320. Your can also start at the bottom and go up For varCounter = 10 To 1 Step -1 When you use a For..Next statement on a set of data it is interesting to count the number of rows and have your counter move from 1 to the number of rows. For varCounter= 1 to varNbRows To see how it is done download my 35 Excel and VBA Macro Tutorials VBA for Excel (macros) Message Boxes In VBA for Excel the message box is the primary tool to interact with the user. You can use it to inform or alert him. The code in VBA for Excel to generate the following basic message box below is: MsgBox "Your message here"

Page 12 of 18 peter@excel-vba.com

XL-mania@yahoogroups.com

When I develop a procedure that takes time to run, I end my code with a basic message box telling the user that the procedure has been executed. MsgBox "The report is ready" or MsgBox "The procedure has been executed you may now go to sheet ""Cover""" or MsgBox "The procedure has been executed you may now go to cell ""A1""" Notice that if you want part of your message to be between double quotes you have to double the double quotes within the message. When a user clicks on a button that triggers a procedure that will do something important like delete all data I always start the code with a message box that asks the user if he is certain that he wants the procedure to run. In this case I use a "Yes/No" message box. Here is how it goes. Sub proDangerousProcedure() Dim varAnswer As String varAnswer = MsgBox("Are you sure that you want to delete all data?", vbYesNo, "Warning") If varAnswer = vbNo Then Exit Sub End if Here the dangerous procedure starts End Sub If you ask me if there is a message box in VBA for Excel or something that you can show to the user while a procedure runs for a long time I am forced to say no. But there is a way around this. Add a worksheet named shWait and insert a picture, a wordart or a message in very large font like "Procedure running" and hide it. Then you can add this code to you long procedure: Sub proLongProcedure() shWait.Visible=True shWait.Select Application.ScreenUpdating=False Here is the long procedure shWait.Visible=False Application.ScreenUpdating=True

Page 13 of 18 peter@excel-vba.com

XL-mania@yahoogroups.com

End Sub You want to display a dynamic message telling the user that a certain number of reports have been updated or that the result of the calculation is so and so or that he may go to such and such sheet to finish the task. For example how do you develop the message "End of procedure. 12 reports have been updated." where 12 is a variable number calculated by the procedure? See how in my 35 Excel-VBA Tutorials Excel VBA Input Box Input boxes have been created to require a SINGLE value from the user. The input box is not very flexible so I very rarely use it. In Excel it is so much easier to require the user that he enters a value in a cell on the worksheet. Read on anyway some elements of code could be useful in other situations.

The input box above is the basic input box and is generated by the following code: Sub proInput() Dim varInput As Integer varInput = InputBox("For what year do you need this report?") Sheets("Intro").Range("A1").value = varInput End Sub A variable is created "varInput" to receive the integer value submitted by the user. Here the value is entered in a cell but it could be used in the rest of a more complex VBA procedure. Note here that the variable is declared as "Integer" so if the user submits a text "string" an error is generated. I show you below how to handle such errors so that the user is not confronted with the VBA error dialog box.

Page 14 of 18 peter@excel-vba.com

XL-mania@yahoogroups.com

You can also use your own title for the input box ("Year" in the example above). To do so, you must use the extended code that follows: varInput =InputBox("For what year do you need this report?","Year") Here is the code to handle errors (canceled or invalid response form the user): Sub proInput() Dim varInput As Integer On Error GoTo addError varInput = InputBox("For what year do you need this report?", "Year") Exit Sub addError: MsgBox "No value submitted or value not an integer, procedure aborted." Exit Sub End Sub Excel Macros : Variables The Variables A variable is an object that you create and in which you can store text (STRING), dates (DATE), numbers (INTEGER, LONG, SIMPLE, DOUBLE) or almost anything else (VARIANT). An ARRAY VARIABLE is a multidimensional variable that you can size to your liking: myVariable(3), myVariable(5,10), myVariable(5,10,10), etc... In the VBE go to Tools/Options/Editor and check the item "Require Variable Declaration". Now at the top of all code windows you will see "Option Explicit". This means that you MUST declare all the variables that you use and there are many advantages to this obligation.

Page 15 of 18 peter@excel-vba.com

XL-mania@yahoogroups.com

Data Types Declare all your variables at the beginning of your procedures and always use one or many upper case letters within the name: Dim varThisVariable as STRING if you misspell the name of your variable within the procedure, Excel wont capitalize the letters telling you that there is something wrong. The prefix "var" will make your code easier to read. I essentially use four types of variables:

STRING

Text, up characters.

to

65,000 I use it for text but also file names, path, worksheet names, workbook names, cells' addresses.

DOUBLE

Number with or without I could also use "Bytes", Integer", "Long" and decimals "Single" but they all have limits. If you use the STRING type for dates, you won't be able to perform calculations on them so use the "Date" type. I use the VARIANT type each time I have a very large number of calculations to perform (more than 2,000 formulas). I bring the range into a VARIANT array, execute the calculations and bring back the range on the worksheet.

DATE

VARIANT

If you use the declaration "Dim varMyvariable.." at the beginning of a procedure, the variable can only be used within this procedure and looses its value at the end of the procedure. If you use the declaration "Public varMyVariable as String" at the beginning of a module (right below "Option Explicit"), the variable can be used in any procedure and any module. The variable keeps its value at the end of the procedure within which it is given a value. I rarely use "Public" because I don't feel comfortable keeping a variable with a value alive. When you declare an array variable, the first element bears the number "0". The Variable varMyVariable(3) includes 4 elements from "0" to "3". If like me you are uncomfortable with a variable varMyVariable(0), you can impose that the first element bears the number "1". In the general declaration (where you find the Option Explicit), write: Option Base 1 In this situation, myVariable(3) contains only three elements.

Page 16 of 18 peter@excel-vba.com

XL-mania@yahoogroups.com

You can carry the value of a variable from one procedure to the other by stocking this value in any cell in the workbook. ex: in the first procedure: Range("A3456").Value=Variable1 in the second procedure: Variable2=Range("A3456").Value

VBA Excel : Forms and Controls Excel VBA Code for Forms and Controls 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 (command buttons, text boxes, list boxes, combo boxes, labels, pictures and other objects. You have learned how to create forms and aadd controls in lesson 9. It is now time to develop some code. You will first create code to call the form. In a module you will create the following procedure: Sub proCityForm() frmCity.Show End Sub You will then add a text box on one of the worksheets and assign this macro to it. To do so you click on the text box that you have added to the sheet from the "Drawing" toolbar and then again on its margin and when the margin becomes a set of small dots you right click on the margin and in the contextual menu you select "Assign Macro" and you follow the instructions selecting "proCityForm". From then on when you left click on the text box the form comes forward. You can also assign this macro to an icon that you add to a toolbar or a VBA command button that you add to the sheet but I much prefer using text boxes. To code for the controls you double click on them. Let's work on the "Cancel" command button first. When you double click on it the form disappears and in the code window you will see this: Private Sub cmbCityCancel_Click() End Sub in between the two lines of code you will write: cbxCity.Value="Select a City" frmCity.Hide

Page 17 of 18 peter@excel-vba.com

XL-mania@yahoogroups.com

because basically what you want to happen when the user clicks on this button is for the form to hide and in case the user has already selected a city you want to erase the value from the combo box. Now the "Submit" button. Let's say that you want the name of the selected city to be transferred to cell C4 of the sheet shReport when the user clicks on the "Submit" button. Double click on it and in between the two new lines of code write: shReport.Range("C4").value=cbxCity.value cbxCity.Value="Select a City" frmCity.Hide Finally in the combo box you want to offer to the user a list of city. The VBA code to do such a thing has to be developed in the "Activate" event of the form itself. First enter your list of cities on a sheet called shParameters in cells A1 to A5 for example. Come back to the VBA and double click on the form itself two lines of code will appear: Private Sub UserForm_Click() End Sub Erase them and go to the small drop down list located above the code window to your right and select the event "Activate" two new lines of code appear: Private Sub UserForm_Activate() End Sub Between these two new lines you will write: shParameters.Activate cbxCity.ColumnCount = 1 cbxCity.RowSource = "A1:A5"

Page 18 of 18 peter@excel-vba.com

Você também pode gostar