VBA Tip Sheet
VBA Tip Sheet
AUTO RUN............................2
ACTIVE CELL..........................2
CARRIAGE RETURN...............3
COPYING A RANGE...............3
COUNTER.............................3
CURRENT DATE.....................4
EMAILING WORKBOOK.........6
EDIT MACROS.......................6
ERRORS IN MACROS.............6
ERROR TRAPPING.................7
EXCEL FUNCTIONS................7
FLICKERING SCREEN..............7
FUNCTIONS..........................8
GOTO (A RANGE)..................8
GOTO SHEET.........................9
HIDING SHEETS.....................9
HIDING EXCEL.......................9
INPUT BOX...........................9
INSERTING ROWS...............10
Page 1 of 21
JOINING TEXT TOGETHER....10
KILLING FILES......................10
LOWER CASE.......................11
MESSAGE BOX....................11
MODELESS FORMS..............12
RANDOM NUMBERS...........13
RANGE NAMES...................14
RESIZING A RANGE.............14
ROUNDING NUMBERS........14
SAVING A FILE.....................15
SECURITY IN EXCEL.............15
SENTENCE CASE..................16
TEXT MANIPULATION.........17
TEXT BOX CALCULATIONS (IN USER FORMS) 17
TIMER.................................17
TITLE CASE..........................18
UPPER CASE........................18
USER FORMS......................18
VBYESNO............................19
Page 2 of 21
Auto Run
Making your macros run automatically when opening your workbook. You can either use the Auto Open
method or the Workbook Open method. These macros will display the message "Hello" when you open the
workbook.
Sub Auto_Open()
Msgbox "Hello"
End Sub
This code would be located in the module. However if you use the second method, the code must be in the
workbook (double click "This Workbook" in the explorer window). Click on the drop down list (that says
General) and select Workbook. Click on the drop down list (that says declarations) and select Open.
Private Sub Workbook_Open()
Msgbox "Hello"
End Sub
Active Cell
An active cell is the current cell that is selected. This term is used in many macros. This can be used as a
marker. A good example is when you need to move from your current cell. Refer to Moving your cursor
macro.
Copying A Range
Copy data from a specific range can be done with this macro. Here data is copied from the current sheet to
the activecell. (Refer to Active Cell)
Sub CopyRange()
Range("A1:A3").Copy Destination:=ActiveCell
End Sub
To copy from a range in another sheet (eg Sheet3) to the active cell you need to change the code to;
Sheets("sheet3").Range("A1:A3").Copy Destination:=ActiveCell
Counter
To use a counter in your macro, just assign any cell to retain the value. In this example the cell A1 is
chosen. Each time the macro is run, it adds the value 1 to the cell A1.
Sub Count()
mycount = Range("a1") + 1
Range("a1") = mycount
End Sub
Current Date
It's a good idea to insert the current date when you save the file so that you can tell if it's the latest version.
Of course this is shown under file properties but how many people know where to find it? You could also
put the current date in the footer of your print out. It is ideal if the date does not change unless the file is
saved. You can use this code. (On the drop down list that says declaration, select before save and you will
see the 1st line of code shown below - more details refer to Auto Run macro)
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Range("A1") = Now 'Select any cell you want
End Sub
Emailing Workbook
To email your current workbook the following code.
Sub Email()
ActiveWorkbook.SendMail recipients:="[email protected]"
End Sub
EDIT macros
Refer to Text Manipulation.
Errors in macros
Ever had a macro running perfectly one day and the next day errors keep on popping up even though you
never made changes to that macro? This is no fault of yours. Due to the excel VBA design, macro files get
badly fragmented due to heavy editing of macros, insertion of modules & userforms. What you need to do
is copy your macros else where, delete the macros, save the file without macros. Open the file again and
import the macros and save it once more with the macros. You macros will run properly until it gets
fragmented again at a later stage.
Error Trapping
Trapping errors are important as users can do marvelous things to mess up you macros. Here you can use
either of these 2 statements.
- On Error Resume Next OR
- On Error Goto ErrorTrap1
... more lines of code
Exit Sub
ErrorTrap1:
... more code (what to do if there is an error)
The first statement will allow the macro to continue the next line of code upon hitting an error but the
second statement will run an alternative code should there be an error.
Excel Functions
Using Excel functions in VBA is almost the same as using them in a spreadsheet. For example to round an
amount to 2 decimal places in a spreadsheet would be;
=round(1.2345,2)
In VBA you would need to use the term Application followed by the function ie;
ActiveCell = Application.round(ActiveCell, 2)
For more examples see Rounding Numbers
Flickering Screen
Sometimes when you run a macro, the screen flickers a lot due to the screen updating itself. This slows the
macro done especially when the macro has a lot of work to do. You need to include the statement as
shown below.
Also see Deleting Empty Rows
Application.ScreenUpdating = False
You need to set the screen updating back to true at the end of the macro.
Functions
Creating function is useful as complicated formulas can be made easier in code than in a spread sheet.
Formulas can be protected so that users cannot see or modify them. The example I use will calculate tax
using the Select Case Statement. Here's the scenario.
First $2500 is tax free.
Next $2500 is taxable at 5%.
Anything above $5000 is taxable at 10%.
In cell A1 type Income and in cell B1 type in your income in numbers say $20000.
In cell A2 type Tax payable and in cell B2 type =tax(B1).
Put the following code in a module. The tax payable here would be $1625.
Public Function tax(income As Single)
Select Case income
Case Is <= 2500
tax = 0
Case Is <= 5000
tax = (income - 2500) * 0.05
Case Else
tax = (income - 5000) * 0.1 + 125
End Select
End Function
Goto (a range)
To specify a macro to go to a specific range you can use the Goto method. Here I have already named a
range in my worksheet called "Sales". You may also use an alternative method ie the Range select method.
Naming a range in excel is recommended rather than specifying an absolute cell reference.
Sub GoHere()
Application.Goto Reference:="Sales" OR Range("Sales").Select
End Sub
Hiding Sheets
To hide your worksheet from users you can use the following code.
Sub HideSheet()
Sheet1.Visible = xlSheetVeryHidden
End Sub
If you hide your sheets this way, users will not be able to unhide them using the menus. Only using VB
codes will be able to display the sheets again.
Hiding Excel
You can hide the Excel application with this macro. This disables the user from using the excel menus.
Don't forget to set it back to visible.
Sub HideExcel()
Application.Visible = False
End Sub
Input Box
When you need to get input from users, you can use input boxes. This macro will ask for the user's name
and will display a message "Hello" plus the user's name.
Sub GetInput()
Dim MyInput 'This line of code is optional
MyInput = InputBox("Enter your name")
MsgBox ("Hello ") & MyInput
End Sub
Inserting Rows
To insert rows required by a user is easy. Here the input box is used so that a user can define the number
of rows required.
Sub InsertRow()
Dim Rng
Rng = InputBox("Enter number of rows required.")
Range(ActiveCell.Offset(0, 0), ActiveCell.Offset(Rng - 1, 0)).Select
Selection.EntireRow.Insert
End Sub
Here the macro uses the range technique where a range is first selected and then subsequently rows are
inserted.
Killing Files
Killing or deleting files is easy. However the files must not be in used.
Sub Killfile()
Dim MyFile As String 'This line of code is optional
On Error Resume Next 'On hitting errors, code resumes next code
MyFile = "c:\folder\filename.xls"
kill MyFile
End Sub
Wildcards can be use. Replace the file name with * (use with caution!).
Killing The Current File
Killing the current file you need to change it's status to read only.
Sub Killed()
Application.DisplayAlerts=False
ThisWorkbook.ChangeFileAccess xlReadOnly
Kill ThisWorkbook.FullName
ThisWorkbook.Close False
End Sub
Lower Case
To change text in a selected range to lower case use this code.
Sub LowerCase()
Dim cell As Range
For Each cell In Selection.Cells
If cell.HasFormula = False Then
cell = LCase(cell)
End If
Next
End Sub
Message Box
When you need to communicate with users, you can use message boxes. This macro will display a
message "This macro is created by Julian". The Message Box appearance can be customised to show
whether it is Information, Critical Messages. Here the icon in the message box would be different. The
buttons can also be customise to show extra Yes, No, Ok buttons. (Refer to vbYesNo macro). This macro
will show you 3 different styles.
Sub MyMessage()
MsgBox "This macro is created by Julian"
MsgBox "The icon is different", vbInformation
MsgBox "The top title is different", vbExclamation, "Julian's Tips"
End Sub
Modeless Forms
Sometimes you want to allow users to be able to switch between your form and your spreadsheet by
clicking on either one. All you need to do is set the form property of Show Modal to False or you can try
this. However this is only for Excel 2000 & above.
Sub myForm()
UserForm.show vbModeless
End Sub
Sub up()
ActiveCell.Offset(-1, 0).Select
End Sub
Sub Right()
ActiveCell.Offset(0, 1).Select
End Sub
Sub Left()
ActiveCell.Offset(0, -1).Select
End Sub
Sub UnProtectSheet()
Password = "1234"
ActiveSheet.Unprotect Password
End Sub
Random numbers
For macros to generate random numbers, the code is takes this format - Int ((upperbound - lowerbound +1)
* Rnd + lowerbound). Where the Upperbound is the largest number random number to be generated and
Lowerbound is the lowest.
Sub RandomNo()
Randomize
MyNumber = Int((49 - 1 + 1) * Rnd + 1)
MsgBox ("The random number is ") & (MyNumber)
End Sub
In this case the random numbers that will be generate is between 1 and 49.
Range Names
Assigning range names to a range of cells.
Sub RngName()
Selection.Name = "myRange"
End Sub
Resizing a Range
Resizing a range is simple. You can apply this to inserting rows & columns or to expand a selected range.
This macro resizes the range to 7 rows by 7 columns.
Sub ResizeRng()
Selection.Resize(7,7).Select
End Sub
Rounding Numbers
Here I will show how to perform different types of rounding. Key in 12345 in any active cell and run the
following code.
Sub Round()
ActiveCell = Application.round(ActiveCell, -3)
End Sub
This code round to the nearest 1000 thus giving the value 12000.
Sub SaveName()
ActiveWorkbook.SaveAs Filename:="C:\MyFile.xls"
End Sub
Sub SaveAll()
myFile = ActiveWorkbook.Name
ActiveWorkbook.Save
ActiveWindow.ActivateNext
Do While myFile <> ActiveWorkbook.Name
ActiveWorkbook.Save
ActiveWindow.ActivateNext
Loop
End Sub
Security in Excel
Level 1 - To protect your excel files, there are a few steps required to make it more difficult for other users
to by pass security. To prevent changes made to the worksheet, you need to protect your
worksheet. See protecting sheets. To prevent sheets from being renamed, moved or deleted,
protect the workbook. However protection of worksheets and workbook can easily be hacked
using macros as shown by an Excel developer. I believe the next level of protection is protecting
your macros. To protect your macros, point at your project in the explorer window, right click on it
and select VBA project properties, click on the Protection tab, check on Lock Project for Viewing
and next key in your password and you're done. Now the project cannot be viewed or amended.
Level 2 - The next step is to force the user to enable your macro when opening your file. The best way is
to use a macro to hide the important sheets (see Hiding sheets) when saving your file. Upon
opening the file, a macro will be used to unhide these sheets. If the user disables the macros
when opening the worksheet, they will not be able to view your worksheet unless they allow the
macro to run.
Level 3 - The final step is to put an expiry date for your worksheet or your macro. However this has a draw
back as the user may change the system date of the computer to by pass the step. Alternatively
you can use a counter (Refer Counter Macro) to allow a fixed number of access to your
worksheet or macro. Here you need to save the counter value each time the file or macro is
used. Upon reaching the defined limit, disable the macro or disable the access of your
worksheet.
The steps mentioned above are not 100% fool proof. But it will keep normal users out but not hackers and
crackers. Here I will not supply the code as this can be lengthy and may be difficult to understand but I
believe these steps may be useful to some of you out there.
Sentence Case
To change text in a selected range to sentence case use this code.
<> Sub SentenceCase()
For Each cell In Selection.Cells
s = cell.Value
Start = True
For i = 1 To Len(s)
ch = Mid(s, i, 1)
Select Case ch
Case "."
Start = True
Case "?"
Start = True
Case "a" To "z"
If Start Then ch = UCase(ch): Start = False
Case "A" To "Z"
If Start Then Start = False Else ch = LCase(ch)
End Select
Mid(s, i, 1) = ch
Next
cell.Value = s
Next
End Sub
Select Data Range
This is a useful when you need to select the whole range of data to copy to another sheet
(especially a large range).
Sub SelAllData()
Application.ScreenUpdating = False
Dim myLastRow As Long
Dim myLastColumn As Long
Range("A1").Select
On Error Resume Next
myLastRow = Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row
myLastColumn = Cells.Find("*", [A1], , , xlByColumns, xlPrevious).Column
myLastCell = Cells(myLastRow, myLastColumn).Address
myRange = "a1:" & myLastCell
Application.ScreenUpdating = True
Range(myRange).Select
End Sub
Text Manipulation
I received many queries regarding text manipulation. Here are some useful text functions which you could
use to EDIT your text.
Sub myEdit()
MsgBox Left("abcd", 2) 'Displays 2 characters from Left
MsgBox Right("abcd", 2) 'Displays 2 characters from Right
MsgBox Len("abcd") 'Displays number of characters
End Sub
Timer
To create a macro to measure time before executing the next line of code use this simple code.
Sub timer()
Application.Wait Now + TimeValue("00:00:10")
MsgBox ("10 sec has elasped")
End Sub
Title Case
To change text in a selected range to title case use this code.
Sub TitleCase()
Dim cell As Range
For Each cell In Selection.Cells
If cell.HasFormula = False Then
cell = Application.Proper(cell)
End If
Next
End Sub
Upper Case
To change text in a selected range to upper case use this code.
Sub UpperCase()
Dim cell As Range
For Each cell In Selection.Cells
If cell.HasFormula = False Then
cell = UCase(cell)
End If
Next
End Sub
User Forms
Adding user forms in your macro is simple. With user forms you can create GUIs (Graphical User Interface)
for user who do not have much excel knowledge and make you excel programs more professional looking.
Go to your Visual Basic Editor window & click on Insert, select user form and a user for will appear along
with the toolbox. Now you can add labels, buttons, text boxes and many more items. The property window
will allow you to customise your user form. To display your user form use these codes.
<>UserForm1.show 'to load form
Unload Me 'to close the form with a macro
Loading User forms with MultiPage
To select a page in a Multipage object is fairly simple. Just remember the page 1 has a value of 0, page 2 a
value of 1 and so forth. To load a form with a specific page in mind, try using these codes.
Sub page2()
UserForm1.MultiPage1.Value = 1 'this sets page 2
UserForm1.Show 'this displays the user form after page 2 has been set
End Sub
vbYesNo
There are times you may want users to click Yes or No. Just insert this line of code. Here the Select Case
statement is used.
YesNo = MsgBox("This macro will ... Do you want to continue?", vbYesNo + vbCritical, "Caution")
Select Case YesNo
Case vbYes
'Insert your code here if Yes is clicked
Case vbNo
'Insert your code here if No is clicked
End Select