Excel’s VBA function allows the user to enhance a workbook by allowing them to automate and manipulate elements and tasks into the excel workbook. Excel uses the programing language visual basic which is an event-driven programming language that is user friendly and specifically for beginners. I remember when I first used VBA to automate formatting of data, with a push of the button I saved 15 minutes every day.


Table of Contents

  1. Developer
  2. Range
  3. Range Properties
  4. Cells
  5. Variables
  6. Editor Toolbars and Menus
  7. VBA Logic
  8. Loops & Reports
  9. Events
  10. Workbook Events
  11. Active X Controls
  12. User Forms


Developer

Developer Tab

To enable the developer tab go to File –> Options –> Customize Ribbon –> check Developer box –> OK.

Dev Tab
Enable the developer tab


Range

Range Object

The range object is the rows and columns of the element(s). For instance, if I have highlighted the first cell it would be a range of A1. If I highlighted the first three columns and first three rows it would be a range of A1:C3. For multiple columns you just take the first element : then the last element in range.

Sample Range Object
Range of B2:E6


Creating a Macro

To open up the VBA developer IDE(Integrated Development Environment) use the shortcut key alt+F11. Alternatively you can go to the Developer tab and click on Visual Basic.

To write your code you need to create modules. Click on the icon Insert Modules, they look like skittles, then Module. You can have as many modules as you like.

Add module
Adding a module

Your macro code will go in between Sub MacroName() and End Sub keywords. To specify a value to a specific cell use the Range("rowcolumn") = value. To run the macro click play button (green triangle). You can also specify multiple cell ranges using the :. You can set value to strings using the "" ex: Range("a1") = "Hello World!"

First Macro
Coding and running macro
Multiple Cells
Multiple ranges

You can stack multiple commands one right after each other. The compiler will read the code from top down.

Multiple Commands
Multiple commands


Debugging

You can debug each line of code in excel by using the F8 key and watching one by one what happens to the workbook. As your code gets longer there maybe some logic error in your code that needs to be fixed; using the debugger tool will help assist you.

Debugger
Debugger


Saving Macro

In order to save a macro workbook it needs to be saved with the xlsm file extension or else it will not work. So when saving the first time the save as type should be Excel Macro-Enabled Workbook.


Executing Macros

  • alt + F11 and then click play then run
  • on developer tab click Macros icon and then select macro and run (shortcut alt + F8)

There are more sophisticated ways such as clicking on a button or a specific cell etc..


Multiple Cells One Range

You can set values to multiple cells in one range command ex: Range("a1:c4, e3") = 15.

Multiple Cells From One Range Command
Multiple cell values from one range commmand


Named Range

Instead of specifying specific rows and columns in a macro you can set the range to reference a named ranged.

Named Range
Set a named range
Reference Named Range
Reference a named range


Range Properties

Value

To access properties you use the . operator and a list of properties available should pop up. The value property gets the value for the range.

Value Property
Value property


Text

The text property gets the data as a string. If you don’t specify a property the default is the value property.

Text Property
Text property


Row and Column

The row and column property will return the row number and column number back in integer of the range.

Row Property
Row property
Column Property
Column property


Select

The select property sets the cursor location to the referenced name.

Select Property
Select property


Count

The count property counts how many cells are in the referenced range. Note it does not matter if their is data in the cell or not.

Count Property
Count property


Address

The address property of a range returns the location of the row and column as in excel ex: A5. You can specify if you want absolute paths of the row/column by specifying a 1 or 0; absolute includes the $ sign.

Address Property
Address property
Address Property No Absolute
Address property without absolute


Formula

The formula property allows you to set a formula to a specific cell.

Formula Property
Formula property


Number Format

The number format changes the format of the value from general to currency, accounting, date, time etc…

Number Formatter Property
Number formatter property


Font Bold, Underline, Italic, Name, Size

The font property you can change the style of the font but it takes a boolean (true/false) value. You can also use Font.Name = "Font Name" to change the font type. Also change the size by using Font.Size = 12.

Font Style Property
Number formatter property


Cells

Cells Object

The cells object is similar to the range object but instead of a range you put in the cell coordinates as integers (row, column). This is great for looping through entire rows or columns. You can substitute the column numbers for letters but need to put them in ""

Cells Object
Cells object
Cells Object
Cells object with letter column


Cell Position

You can reference the cell’s position by specifying the integer location. It starts with the row A1 = 1, B1 = 2, C1 = 3 etc. However, if you select a range and then use the . operator and use cell object it will only count within the referenced range.

Cell Position
Cell Position


Select All Cells

You can select every cell in the workbook by simply not referencing a specific cell; Cells.

Cell Position
Select all cells


Range Object With Cell

Sometimes you will want to select from a specific cell to cell without hardcoding the range. You can do this by using Cell(r,c) as a parameter for the Range() object.

Range object with cell
Using range object with the cell


Variables

Variable Types

The table below shows what data types are supported as well as their memory size.

List of data types


Declaring Variables

You declare variables by using the keyword dim followed by variable name then keyword as followed by data type; dim hello as String, dim x as Integer. Once declared you assign a stored value by using the = operator.

Declare and assign variables
Declare and assign variables


Call A Procedure

To call another procedure (function) use the Call keyword followed by the procedure’s name, ex:Call myMethod. If there are variables declared within the called procedure then the values will be out of scope and not recognized by the compiler.

Call another procedure
Calling another procedure within a procedure


Public and Private Variables

When setting a variable as Public the variable will retain its data and can be used throughout any other module. When setting a variable as Private the variable can only be accessed only within the module it is initialized in.

Public and Private Variables
Declaring public and private variables


Using Constants

Declare constants by using the Const keyword and you must assign data when declaring. Constants cannot be changed. Const PI as Double = 3.14. You can also make the constants public or private.


Concatenate Strings

You can combine two or more strings by using the & symbol. This will also work to combine string variables. text = "Hello " & "World!"


Pass by Value vs Reference

When passing values into a procedure use the keywords ByVal & ByRef to specify how you are passing the variables through. By value means that only the value is being passed and will not change once the procedure is ended. By reference means that any changes made will change the original value.

By reference and by value examples
ByVal does not change but ByRef does change


Editor Toolbars and Menu

File Menu

The file menu you have your basics save, print, remove. The Remove module will delete your file. You can Export your code and save it as a .bas file. You can also Import your written code from a .bas file.


Edit Menu

In the edit menu the List Properties/Methods (ctrl + j) will open a dropdown menu with all of the available options of properties and methods. Another tool is to use the Bookmarks to save the location of a particular code so you can reference it later if need be.


View Menu

View menu has the some useful tools other than adding different menu items to your toolbar. Last Position will move the cursor back to it previous location. Definition opens up a window with a list of all the properties/methods along with a description on each. Object Browser is similar to definition but displays a list of all the objects.

The Immediate button will open up a window where you can change temporary change your code; such as, change a variable’s data. Also in the Immediate window you can write debug.Print varName to display the result.

The Locals window will display information about all of the local variables in the current modules. The Watch Window allows you to select a variable to shadow and displays its changes throughout the code (good for debugging). It will also display vast amount of information that can be toggling the + symbol next to it.


Debug Menu

The Debug menu is really important as it will help you find and fix errors in your code. Step Into when run goes into any methods and runs the code line by line. If you wanted to get out of a method Step Out will get you out of any methods/subs. Run to Cursor will run the code from beginning to where your cursor is.

In addition is you can also add, edit, remove watches. Toggle Breakpoint will run the code up to the breakpoint then wait for you to resume the code until the next breakpoint or end. Set Next Statement will allow you to temporary skip code and jump to the marker (yellow arrow) and start running code from that line.


Logic

Last Row

To find the last row of the data set in your workbook combine these methods and it will return the last row value as an integer ex: lastRow = Cells(Rows.Count, 1).End(xlup).Row. What this does is it goes through all the rows in column one. Then it goes up until it finds the first cell with a value in it.

Find the last row with data
This method helps find the last row with data


Last Column

To find the last column of the data set in your workbook cmbine these methods and it will return the last column value as an integer ex: lastColumn = Cells(1, Columns.Count).End(xlToLeft).Column. What this does is it goes to to the last column then back left to the first cell with a value in it.

Find the last column with data
This method helps find the last column with data


Next Row

To get the next row you simply use the formula for the last row and add 1 to it ex: lastRow = Cells(Rows.Count, 1).End(xlup).Row + 1


Record Macro

Excel give you the ability to record a macro while you perform the function on the physical workbook. It then creates a module with the code written. See sample below on steps to recording a macro.

Hit record
Step 1: Hit record macro on dev tab
Enter macros name and other info
Step 2: Enter macros name and other info
Work on your workbook
Step 3: Work on your workbook until finished
Stop recording
Step 4: Stop recording
Your code will be in modules
Step 5: You can review and edit your code


Absolute vs Relative Reference

Absolute reference is when objects are referring to a specific cell, which is hard coded. When the macro is run it will always reference to that specific cell. Relative reference dynamically changes the location of the cell by using the current position of the cursor as the starting point. To use relative reference make sure to check the Use Relative References button.

Absolute vs relative reference
Absolute on top and Relative on bottom


With and End

If you have multiple commands to execute within a cell its best to use a With & End With block to save repetitive typing and keeping clean code.

With block to save repetitive code
With selects ActiveWorkbook.Workshe... instead of repeating it several times


Comparison Operators

  • = equal to
  • <> not equal to
  • < less than
  • > greater than
  • <= less than or equal to
  • >= greater than or equal to


If Then

Use the If Then keywords to create and execute a conditional statement; if the condition is true. You need to always need to close the conditional block by using End If.

If then conditionals
Use if then keywords to create conditional statements

If you just have one condition to check you can write the if statement, without the Then in one line ex: If Range("c3") = 11 Then MsgBox "YOLO".


Is Not Equal To & Not

You can use the <> is not equal to operator to create the opposite of the equals operator ex: If range("A1").value <> 1 Then etc… You can also you the keyword Not after If to say if cell value is not equal to “x” then execute these commands.

Use <> operator or Not keyword


Else

Use the Else keyword to create a nested conditional statement so that if all the If Then statements are false then the Else statement will run.

Use if then else block


Else If

Use the ElseIf keyword to combine as many conditional statement you need. The structure will start with If condition Then then ElseIf condition Then and finally Else

Using else if


Comparative Operators Text & Numbers

When comparing numbers, if the cell data is text then the compiler will accept it and convert it to a number; however, to prevent this in the If statement use method IsNumeric(cellLocation) ex: IsNumeric(Range("a1")). The And keyword must be used to allow for multiple conditionals where both statements must be true in order for statement to execute.

Compare numbers only
If not specificed the compiler will accept text as numbers


GoTo & Labels

If you have parts of your code that need to be skipped for whatever reason then the GoTo keyword along with labels allow you to do this. The label must be spelled the same and must include at : after it.

Use GoTo command to skip over blocks of code
Use GoTo and labels to skip over code if needed


Select Case

Similar to If Else the Select Case keywords are good for conditionals on a specific value. It makes code cleaner and much easier to read/write than If Else. You must end the block by using End Select.

Use the select case keywords for conditions
Use case statements for single value conditionals


Message Box Options

The message box object can be modified to have several other options; such as, yes and no buttons. Utilizing the options will allow you to create a more visual and user friendly experience. To enable the options you use the function MsgBox("text", options). It is a good idea usually to store the user’s answer into a variable.

Use message box for more visual experience
Use the additional options for message box


Relative Positioning

You can select any cell from your current cursor position using the Selection and Offset(row, column) functions. You don’t have to use selection only you can use the Cells or Range object with the Offset.

Use relative positioning
Offset will allow you to change cell location


Loops & Reports

For Loop

The For Next is a good loop to cycle through a row or column. The formula for For loop is For counter_var = starting_value To ending_value and to increment the counter use Next counter_var.

Sample For Loop
Sample for loop


Simple Report

Using the for loop and conditionals you can create a simple report to grab specific data from the worksheet to be able to print out. The below example will grab data of anything under $500 in sales. To create a new line use the keyword vbNewLine.

Sample report out put to message box
Sample report output to message box


Input Box

Input boxes allow you to receive some data from the user. Use the function inputbox("prompt", Title, "default value") and set it equal to a variable to store the value.

Input box
Input Box

You can convert text to number a couple of ways. The first way is to add 0 to the the number ex: "200" + 0.

Convert text to number
Convert text to number

Sometimes you will have debug error if you cancel out of an input box. To prevent this use the On Error Resume Next to allow the code to continue on error. Also use an If statement to check that the input is not Empty Then Exit Sub.

Input is empty
Prevent empty input value from causing errors


Button

To add a button which executes other code when use the graphical interface in the insert tab and preferably use ActiveX Controls ones. Drag and hold until the size is what you like. To edit the properties right click and select properties.

Button on insert menu
Select graphical editor
Edit Properties
Customize and edit button

To link it to a function use the Call keyword so that when the button is clicked it executes the function. Double click on the button to open up VBA editor.

Code for button
Code for the button

Another way to make buttons is to use the Shapes in the Insert tab. You can then right click and assign a specific macro to it. This allows your buttons to good visually instead of the generic dark gray square buttons.


Report

Below is an example on creating a simple printable report. It is important to use the Set keyword to link worksheets to a variable.

Label worksheet tabs
Step 1: label worksheet tabs

Use Dim to declare variables and link them to specific data in the workbook.

Set worksheets to variables
Step 2: set variables to link to specific worksheet

Since we are now using more than one worksheets we must specify which worksheet we will be using before using functions such as Cells Range etc.

Specify worksheet and code logic
Step 3: Specify which worksheet you are using. Code the logic.

After running the report once the original report will stay. If you add remove data and run the report again you may have data in there from previous runs. it is best to create a function to clear out the old report before running the new one. Use the ClearContents object for that.

Clear out old report
Step 4: Clear out old report before running new one

To automate the movement to the report tab so that the user doesn’t have to manually find it or go there. If sheet is hidden use the Visible object and set it to true. Then you will have to use Select object to move user’s view to the worksheet.

Show report worksheet
Step 6: Show the report worksheet


Printing

You can set a worksheet on print preview mode by using the PrintPreview object ex: wrksht.PrintPreview. It will then automatically create and print preview of the worksheet.

To send the worksheet out to the default printer use the PrintOut(args) object. One property copies: 1 should be set to one unless you want more.


Reverse For Loop

To go backwards in a loop use the Step keyword instead of Then.

Reverse for loop
Reverse for loop


For Each Loop

The for each loop will loop through an entire group of objects. One example is the named table you can loop through the entire table. Use the keywords For Each cell In Range("letters") and then to continue use Next cell. You can exit the loop if need be you can use Exit For.

For Each
For each loop


Do Loop

Do loop keeps looping through until a condition is met. Do loops can go into an infinite loop if you do not give a condition that reaches true and breaks the loop. Use keyword Do and Loop.

Do Loop
Do Loop


Do Loop

The Do Until forces you to specify a condition so that when true it will break out of the loop. You can still have an infinite loop if the condition never reaches true. It checks the condition before entering the loop.

Do Until
Do Until


Loop Until

The Loop Until forces you to specify a condition at the end of the loop; however, it will run the loop block at least once before checking the condition.

Loop Until
Loop Until


Do While

The Do While loop keeps running while the condition is true. This is different such that the condition is already true while the previous loops the condition was false.

Do While
Do While


Loop While

The Do Loop While is similar to the loop until such that, the loop code will run at least once before checking the conditon.

Loop While
Loop While


Exit Loops

To exit loops anywhere in between use the Exit Do keyword.

Exit Do
Exit Do


Events

Intro Events & Selection Change

Worksheet events occur whenever something happens on the worksheet. There are other methods to trigger a macro besides just tying it to a button.

In the VBA editor change from General to Worksheet and you will see a sub for Worksheet_SelectionChange. Every time you click on a different cell of the worksheet this sub will run the code inside it.

Intro to events
Worksheet_SelectionChange sub will run each time you select cell on worksheet

The sub passes in an argument called Target that will get the value of the cell that the cursor is moved to. You can use target.properties to access information about the targeted cell.

Intro to events
Use target variable to extract information from the highlighted cell


Activate Event

The activate event will trigger when you change worksheet tabs. You must select Worksheet and then Activate.

Activate event
Use activate to trigger when you switch tabs


Deactivate Event

The deactivate event will trigger when you leave current worksheet tab for another one. You must select Worksheet and then Deactivate.

Deactivate event
Use activate to trigger when you switch tabs


Before Delete

The BeforeDelete event will trigger before deleting a worksheet. It doesn’t prevent you from deleting just executes the code before you delete. You must select Worksheet and then BeforeDelete.

Before Delete
Before delete


Before Double Click

The Before Double Click event will trigger before the double click action takes place. There is an additional argument called Cancel that is passed in and its of a boolean value. If cancel is false after the double click code runs the cursor will then place cursor ready to edit contents of the cell clicked; to stop this make cancel true.

Before Double Click
Before Double Click


Before Right Click

The Before Right Click event will execute code before the original right click function works. Setting cancel to true here will prevent the original right click menu from popping up after.

Before Right Click
Before Right Click


Calculates Event

The Calculates event will recompute all the formulas for the worksheet. The example given by Microsoft was to autofit the columns A through F.

Calculate Event
Calculate Event


Disable Events

You can disable events on a workbook by using the Application.EnableEvents object and setting it to false.

Disable Event
Disable Event


Change Event

Change event will run whenever any cell value changes.

Change Event
Change Event checking single cell value

You can also compare with a range instead of just a single cell. You will need to use the intersect function to compare your target and then the range to compare it to.

Change Event Intersect
Change Event comparing a range


Follow hyperlinks will get a hyperlink in a cell and pass it as an argument. Using the target you can select from a list of properties to edit and manipulate the hyperlink.

Hyperlink
Hyperlink


Workbook Events

Workbook Open

Workbook events are like worksheet events but they effect the entire workbook. In the VBA editor select the ThisWorkbook icon to create macros for the entire workbook. The Open event runs as soon as the workbook is open.

Open Event
Open Event


Workbook Activate

Workbook Activate event runs once you click on the workbook. If you have 2 workbooks open and switch between them each time you lose focus and come back the Activate macro will run.


Before Save

Workbook Before Save will trigger when you click the save button and then execute the macro before saving. If cancel is set to true then it won’t save.

Before Save Event
Before Save Event


After Save

Workbook After Save will trigger after the workbook tries saving. It returns a Success argument that is true/false depending on if the workbook saved successfully.

After Save Event
After Save Event


Before close

The Before Close event runs before you close the workbook. It also passes in the Cancel argument as a boolean.

Before Close Event
Before Close Event


Before Print

The Before Print event runs before you print a worksheet. It also passes in the Cancel argument that if set to true won’t allow anyone to print. This is good in preventing confidential data for being allowed to print.


Workbook Deactivate

The Workbook Deactivate event is similar to the Workbook Activate event but triggers right after you lose focus of the workbook.


New Chart

The New Chart event is when you create a new chart. The Ch argument is a chart object. Whenever you create a new chart inside the workbook the values assigned will become the default values of the chart. If you need to figure out how to adjust some of the other chart properties its best to record a macro and then reverse engineer it.

New Chart Event
New Chart Event


New Sheet

The New Sheet event runs everytime you create a new worksheet. You can edit the properties of the new sheet by using the passed in object Sh. For example you can edit the font type on all cells to be says bold ex: Sh.Cells.Font.Bold = True.


Sheet Activate

The Sheet Activate event triggers each time you are in focus on the worksheet. The object passed in Sh is the current sheet.


Sheet Before Delete

The Sheet Before Delete runs when any worksheet on the workbook is deleted. There is no Cancel variable to prevent deletion.


Sheet Before Double Click

The Sheet Before Double Click runs when you double click anywhere on the entire workbook. The arguments passed are worksheet, target, and cancel options.


Sheet Before Right Click

The Sheet Before Double Click runs when you right click anywhere on the entire workbook. The arguments passed are the worksheet, target, and cancel options.


Sheet Calculation

The Sheet Calculation runs when you edit any formulas anywhere in the entire workbook.


Sheet Change

The Sheet Calculation runs when you change any value of a cell in the entire workbook


Sheet Deactivate

The Sheet Deactivate code runs when you leave the current worksheet to another one.

Sheet Deactivate
Sheet Deactivate


Sheet Selection Change

The Sheet Selection Change runs anytime you move your cursor to a new cell position anywhere in the entire workbook.


Window Activate

The Window Activate only triggers when the workbook itself is activated and in focus.


Window Deactivate

The Window Activate only triggers when the workbook itself is deactivated and loses focus.


Window Resize

The Window Resize runs each time you resize the workbook. It passes in a window object Wn that you can get height, width, size and other information about the window.


Active X forms allow a lot more customization and give you a ton more information than a simple form control. You are able to change everything from the name to the mouse cursor. To get the information right click and select properties. Also active x allows you to select from various different types of events.

Active X Form
Active X Form

Below is an example of the code you can use to create a simple wage calculator. With a click, double click, or other events of a button you can compute multiple cells. This is also useful so that formulas cannot be accidentally erased when hardcoded into the excel cell.

Active X Form Calculator
Active X Form Calculator


Key Down/Press Event

The keydown and press events occur whenever a key has been pressed and will return an integer value corresponding to the key. Click Here For Complete List of KeyCodes. The variables that are passed in is the KeyCode as an integer and Shift which checks to see if shift was held during the event.

Key Pressed Example
Key Pressed Example

The key press event is similar to keydown but it returns a value based on the ASCII code value. Click Here For The List of ASCII Codes.


Mouse Move & Application Statusbar

The mouse move event triggers when your mouse moves onto the object. The additional arguments passed give you the x and y coordinates.

Mouse Movement
Mouse Movement

You can add a status bar message by using the Application.Statusbar keyword. This will provide additional information to the user. You can set the value to false to get ride of the statusbar message.

Application Statusbar
Application Statusbar


Mouse Up/Down & Left Middle Right Click

You can get specific on when to execute the code depending on after mouse has been clicked or as soon as it is on the down phase. Left, Right and Middle clicks are pretty self explanatory.

Mouse Click
Mouse Down Event


GotFocus and LostFocus

The GotFocus event occurs when you click on the button. The LostFocus event triggers when you click away or tab away from the button.


Checkbox

The checkbox object only allows for a true or false value. Using the keyword Me is equal to this and reference’s the current worksheet. You can combine other forms and use the checkbox’s value.

Checkbox
Checkbox by using its value

You don’t need to be dependent on a button to utilize the checkbox. You can trigger codes based on the interaction with the checkbox.

Checkbox example
Checkbox by user interaction


Linked Cell

You can link a specific cell to a form. For example the checkbox’s value can be linked to cell “a1” and whenever you check/uncheck the box the value in “a1” will change. To link a cell right click the form and in properties under LinkedCell enter the cell value.

Linked Cell
Link a cell to a form


Option Button

The option button is more of a grouping setting; such that, you should use more than one. When the option button’s are grouped together you may only select one. To group option buttons you need to first cntrl + click to select the options you want in the group then click on properties in the developer tab. Fill out the property called GroupName to create the group.

Creating a group list
Creating a group list

To neatly format the icons you can select the option buttons and go to Format and under Align select the appropirate function in most cases its Algin Left. To manually align for the small mm offsets you can use the arrow keys. Another tip on selecting the entire group as one unit.

Below is a sample program on how you can use conditions with the optionbox forms.

Move selection app
Movie selection app

You can create a checker to see that the user in fact selected the required conditions in order to run. Have an If statement checking to see that at least one of the choices is selected; use the Or keyword in the conditional IF x or y or z. Another way is you can set the confirmation button to invisible and when the conditions are met change it to visible.


Spin Button & Textbox

The spin button are arrow buttons that are either up and down or left and right and cycle through a list of choices. The two most common events are spin up and spin down.

Spinner
Spin form

When cells are empty the compiler automatically thinks its 0 this is why a textbox is great form to be combined with the spinner. Textbox always contains a text value so adding a number to it will not work and throws an error. You can use the On Error Resume Next and/or check to see if text is empty. Another method is to check to see if it is a numerical value using IsNumeric.

Spinner
Spin form

Spin buttons can also be used for more than just numbers. You can convert the number into a date and use that to display the date type. You can use the CDate() function to convert into a date.

Spinner
Convert textbox into a date


Labels

You can create labels to make your sections more descriptive. You can also add a picture and change the look and feel of the label in the Properties.

Label
Using Labels


ComboBox Fill with List Fill Range

The list fill box is good to create a dropdown list of categories for the user to select from. You setup a group and in properties set the group name into ListFillRange. The combo box can have a list and or textbox.

ComboBox
Lists

Sometimes you will need to have a dynamic range so that when new records are added it automatically picks up. To do this click alt + I + N + D for the names manager edit the value to offset(starting cell, move down #, left or right #, how many rows wide? use counta(get count of nonblank cells) - header(1), how many column wide (1))

Dynamic Range
Dynamic Range

With combo boxes you can have multiple columns. In the ComboBox properties change the column count and expand your named range to include more than one columns.

There are more customizable ways to add items to your combobox. Using the .AddItem function. To clear up all entries inside the combobox use the .clear function.

Add Item
Add items to combo box

If you have multiple columns and need to add items you will have to use some array manipulation. Arrays start with 0.

Add Item
Add multiple columns to combo box


List Box

List box is a box with a list in it. You can specify the group name in the properties as well as the number of columns. You can adjust the column widths also just put ; in between each column. If its a named range you can turn on the property of ColumnHeads to true.

listbox
List Box

The list box takes the value of whatever line the user clicks on. Columns are in array format starting with 0. You can have a linked cell or you can put events on it using click events.

To use the other columns data you will have to use the list and find the index.

listbox
Extracting data from list box

To make the listbox dynamic you can use the AddItem function. You can also hide columns but keep value by changing the property of the column’s width and setting it to 0pt


Scrollbar

The scrollbar can be used to scroll through either data or values. Using the properties menu you can change the min and max properties. You can also change the small changes (when arrow is pressed) or large change when the middle of the scroll bar is pressed.


Image Control

You can create an image and use that as a button as a control. One use is to link it to a webpage using FollowHyperlink ("http://www.google.com")


Toggle Button

The toggle button has only 2 values a true or false and you can click it to make it true and click again to make it false.


User Forms

Hide Show & Unload

To get to the userforms menu click on the icon and a new editor will open up as well as creating a new forms folder. To get form toolbox you can go to View then Toolbox to bring it up.

User form menu
User form menu

You can hide and show a user form by using the Hide and Show commands.

Hide Show
User form menu


Status Box

User form boxes also have properties you can use F4 shortcut. To populate data into the form use the Initialize event to load data on startup. You can either use the AddItem function or alternatively go to properties window and selected a range or named source into the RowSource box.

Hide Show
User form menu


New Data

From the user entry from you can create a button to update the data records. To do this you find the last row of the data set then extract each data from the form and add it to the excel sheet. If you have numbers you will need to change the format to number.

Add new data
Add data to data set
Add new data result
Added new data row to data set


Convert Text to Numbers

When you extract data from the user form it will be in text format and will need to be converted if you need it to be any other type such as numbers. The best way to do this is to +, -, /* or // to change the text into a number.


Tab Order

To set the tab index order so that when a user is typing and hits tab it goes to the next box you need to change the properties of each text box in sequential order. Change the TabIndex field and start with 0, 1, 2 and so on.

tab index
Tab Index and order


Default Value

To set a default value in a textbox set it in the caption property.


Prevent Duplicates

Prevent duplicate records by creating a loop and checking to see if ID created matches.

tab index
Tab Index and order


Edit Mode

Your form should also be able to edit a record. To do this you should create an edit button and combine it with a dropdown list of all the records (RowSource). You should create a dynamic named range.

Create Button
Create edit button

Once the record has been added its best to clear out and blank the text boxes by just setting them to blank string. To edit create a loop and compare a unique ID to see if it matches. You may need to convert number to text and the easiest way to do that is just add & "" to convert it to a text. When saving it would update the record.

Edit existing record
Edit existing record
edit3
When saving you need to stop firing the change event
User Form
User Form


Reports w Filters

You can create another userform that can extract the data and create a useful report.

report filter
User Reports
report filter
User Reports
report filter
User Reports
report filter
Dynamic Filters
report filter
Dynamic Filters

Remember to clear our last report before running another one.

Clear Report
Clear Report