Essntl Snippets VBA CL
Essntl Snippets VBA CL
Disclaimer
All the material contained in this book is provided for educational and
informational purposes only. No responsibility can be taken for any
results or outcomes resulting from the use of this material.
While every attempt has been made to provide information that is both
accurate and effective, the author does not assume any responsibility
for the accuracy or use/misuse of this information.
https://www.udemy.com/u/danielstrong3/#teaching
www.youtube.com/ExcelVbaIsFun
www.ExcelVbaIsFun.com
VBA is the window into Excel's soul - unveiling the Wizard behind the
curtain. Okay, it's actually some simple code that allows you to
Automate almost anything in Excel.
This book assumes you know some Excel VBA Basics, at least enough
to know how to make a new Sub that you can shove code into. If not,
please click here to find out how this works:
http://www.youtube.com/watch?v=AIhKNNXzZLM&list=PLw8O1w0Hv2
ztGjIkrW7suD6oNDaOk3vbR&index=1 This book is interactive – all
sample materials are available in the Sample Workbook, so you don’t
have to start from scratch and can benefit from real life examples.
Either way, enjoy the code snippets and remember – You CAN do anything you set your
mind to. You ARE a success, just believe it and think like that no matter what. Remember,
the mind controls the body, so create your reality through positive thoughts. Enough about
that, let’s get coding!
This one is super-duper essential! Example: To find the last row in use on column one:
LastRow = ThisWorkbook.Sheets(“Sheet1”).Cells(Rows.Count,1).End(xlUp).Row
If you need to know what the last used column number is, or how many you’ve got, use
this code snippet! This is if you want the last used column on Row 1.
LastCol = ThisWorkbook.Sheets(“Sheet1”).Cells(1,Columns.Count).End(xlToLeft).Column
When you’re wanting to write to the next available Row, this code snippet is a life saver!
Example: To find the next available row in column one:
NextRow = ThisWorkbook.Sheets(“Sheet1”).Cells(Rows.Count,1).End(xlUp).Row + 1
Especially Cool when you have a zillion sheets (like reports) that you only need unhidden
when you’re using them.
Right-click on the sheet you want and click on “View Code”. Now copy/paste this code in
there (Assuming the sheet you want to hide is called HideThis, otherwise use your sheet
name):
Click
any
Now “HideThis”
other
sheet is gone!
sheet
This will save a gazillion keystrokes of the lifetime of a programmer. Instead of typing this
to change cell A1 to “Dates”, and then change b1 to “Salesman”, and c1 to “Sale Amount”:
ThisWorkbook.Sheets(“Sheet1”).Range(“A1”) = “Dates”
ThisWorkbook.Sheets(“Sheet1”).Range(“B1”) = “Salesman”
ThisWorkbook.Sheets(“Sheet1”).Range(“C1”) = “Sale Amount”
ThisWorkbook.Sheets(“Sheet1”).Range(“D1”) = “Commission”
Dim ws as worksheet
Set ws = ThisWorkbook.Sheets(“Sheet1”)
ws.Range(“A1”) = “Dates”
ws.Range(“B1”) = “Salesman”
ws.Range(“C1”) = “Sale Amount”
ws.Range(“D1”) = “Commission”
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet3")
LastRow = ws.Cells(Rows.Count, 1).End(xlUp).Row
For x = 2 To LastRow
If ws.Cells(x, 3) > 20 Then
Debug.Print ws.Cells(x, 1) & " is " & ws.Cells(x, 3) & “ years.”
End If
Next x
This code loops through row 2 through 9 and finds those that are greater than 20! If they
are, it spits out something like: “John is 56.77 years”
This is handy when you have a named range in your workbook that you want to refer to.
This will go through each Cell in the range, left to right, top to bottom. In the example
below, we have a custom list of States that we’d like to loop through, named “States_List”,
found on sheet “LNR”.
If you want to cycle through each worksheet to see if one of them has this property or this
one’s visible or not, or see which one starts with this letter – you get the picture. This code
snippet allows you to loop through each worksheet in your workbook. Nifty!!
In this example, we want the names of each sheet printed in the Immediate Window. Use
this (it’s a dandy):
Dim ws As Worksheet
Sometimes you need to go through each item in a ListBox, maybe to refresh or tweak the
list. Maybe you’re filtering to remove an entry or two. In this example, we’ll count the
occurrences of the name “Dan” in our list. We’ll put a click event in our ListBox
(lbxNames) to trigger when clicked. Whichever name we click on will be counted.
For x = 0 To Me.lbxNames.ListCount - 1
If Me.lbxNames.List(x, 0) = Me.lbxNames.Value Then
myCounter = myCounter + 1 'increment each time it matches
End If
Next x
'here at the end, fill the label with the number
Me.lblCount = myCounter
End Sub
When you’re dealing with files and folders with your macros, it’s nice to have this in your
back pocket, in case you need to have VBA search through each file name and analyze
them. Maybe you’re searching for files that end in .mp3, or maybe you’re needing to find a
specific file, maybe you want any file that contains a term or string of text you need. Who
knows, play around with it!
In this example, we’re going to fill a listbox with anything on the Desktop that ends in
“.mp3”. Let’s see how many songs are on the Desktop! Try this macro within the Sheet
that your Listbox lives in.
Sub FindMp3s()
Dim FSO As Object
Dim File As Object
Dim Fldr As Object
Set FSO = CreateObject("scripting.FileSystemObject")
Listboxes are amazing, because you can emulate tables with them and make it look like a
portion of a worksheet, allowing the viewer to select one or more records and do stuff with
them! You can Fill a ListBox with a named range or with a regular range by using the
RowSource (on a Userform) or the ListFillRange (on a Sheet). But here’s how to
customize the results in your ListBox. In this example, we fill a ListBox with the records
that say “Marvin” in the name column.
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("MrvnSht")
wLR = ws.Cells(Rows.Count, 1).End(xlUp).Row
For x = 2 To wLR
If ws.Cells(x, 1) = "Marvin" Then
'add to lbox
Me.lbxMarvin.AddItem ws.Cells(x, 1)
Me.lbxMarvin.List(Me.lbxMarvin.ListCount - 1, 1) = ws.Cells(x, 2)
Me.lbxMarvin.List(Me.lbxMarvin.ListCount - 1, 2) = ws.Cells(x, 3)
Me.lbxMarvin.List(Me.lbxMarvin.ListCount - 1, 3) = ws.Cells(x, 4)
End If
Next x
Comboboxes are called drop-down menus/boxes in the non-VBA vernacular. They are
actually a combination of TextBox and ListBox, because although you may select one of
the items as a regular dropdown or list, you may also type freely and it will help you auto-
select the item you want, but you can also veer from the list and enter something else.
Here’s a code snippet where we fill a combobox with entries that are “Active” (records that
have the letter “A” in the Status column).
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("blah")
wLR = ws.Cells(Rows.Count, 1).End(xlUp).Row
For x = 2 To wLR
If ws.Cells(x, 3) = "A" Then
'add to lbox
Me.cmbStatus.AddItem ws.Cells(x, 1)
End If
Next x
Say you have a UserForm and 2 ComboBoxes. The First one will have the 3 main
categories, Medical, Engineering and IT. Based on which is selected the other 2
comboboxes will fill with those lists – one a list of Medical types, the next Engineering
types and so on. We’ve named the ranges as follows: “Professions”, “Medical”,
“Engineering”, and “IT”. We’ll use the RowSource property in the userform combobox to
set the lists this time, rather than using .AddItem like last time.
We’ll put the code in the change event for the first combobox named “Combobox1”, this
way anytime someone clicks the first combobox, the next one will be changed to include
those specific entries for that selection.
So when “IT” is selected in Combobox1, Combobox2 now is blanked out and filled with
the list called “IT”.
Spin buttons are basically left/right arrows or up/down arrow sets. You can direct what the
spin-up click does or the spin-down. Spin up controls the right click if you have it set
horizontal (right/left) and spin-down controls the left click if horizontal. This is fun to play
with. In the example below, we’re going to make the textbox on the userform named
“Userform1” go up in value when you spin up and go down 1 when you spin-down. The
Textbox is called “tbQty” and the spinbutton is called “sbQty”
When using a spinbutton to increase/decrease the date, we’ll use a similar procedure as
increasing/decreasing the value by one. One difference is that we’ll be using “IsDate” and
“CDate” in order to identify or convert dates (respectively). Keep in mind you can use this
code to increase weekly (+/- 7), biweekly (+/-14), and there are ways to get the beginning
date of the next/previous month or the end of a month. In this specific example, we’ll
increase or decrease the date by one day. Let’s start with Valentines day (Feb 14) 2014!
We’ll name the textbox “tbDate” and the spinbutton “sbDate”. Double click on the
spinbutton but change the event to “SpinUp” and “SpinDown” instead of the change event
that’s default. Here’s the code I use for each.
or
The first line tells it to not freak out if something’s wrong, like a textbox being blank or
NOT a date, etc. The next line tells it to take whatever’s in the textbox and have it become
whatever it is (converted from text string to a date using CDate) plus or minus one day.
Navigation is another big deal in programming. Here’s a starting point on how to navigate
and manipulate the Userform tabs using a spin button. Please note that the Multipage in
the example has 3 tabs, so the Multipage values are 0, 1, and 2. Here are the complete
macros for the spin-up and spin-down snippets within the userform. The spinbutton is
named SpinButton1.
Scroll bars can be used pretty similarly as the spin buttons, the main difference being that
Scroll bars can be dragged to pinpoint a value in addition to the top/bottom ends. This is
fun to play with and manipulate. In this example, we’ll pin (link) a cell to receive the value
of the scroll bar and we’ll set the scroll bar to be from 1 to 100.
Now when you click up or down OR drag the scrollbar middle piece, the value in cell A1
will reflect it. Try putting a function in cell B1, like =A1 * 4.29 to see how many
weeks are in the number of months in A1.
In design mode, double click on the scroll bar and put this code in the Sub, assuming the
scroll bar is ScrollBar1. Otherwise adjust this code:
Either way, your sheet will look like this as you scroll. . .
For x = 2 To wLR
If ws.Cells(x, 3) = "A" Then
'add to lbox
Me.cmbStatus.AddItem ws.Cells(x, 1)
End If
When a macro is running it has to obey your commands in order. It usually runs these
commands much faster than the eye can see, and sometimes faster than the screen can
keep up with. In order for the screen to process all the changes, sometimes this slows
down the progress of the macro in order to compensate for the slow screen. The solution
is to allow the screen to NOT need to keep up with the macro. Disable the screen’s
updating until the macro has run its course. Now it can go fast and not have to worry
about whether the screen is keeping up! Put this at the beginning and ending of your
macro:
Beginning:
Application.ScreenUpdating = False
EXAMPLES:
Sub mySlowMacro()
For x = 2 to 10000
Cells(x,1) = x
Cells(x,2) = x + (x*.10)
Next x
End Sub
Sub myFasterMacro()
Application.ScreenUpdating = False
For x = 2 to 10000
Cells(x,1) = x
Cells(x,2) = x + (x*.10)
Next x
Application.ScreenUpdating = True
End Sub
Sometimes the macro runs slowly because every time a cell changes in Excel, the
workbook decides to recalculate EVERY CELL in the workbook so it won’t miss anything
important it needs to know. . . When we’re running a gazillion cell changes for report
generation, we don’t want it recalculate a gazillion times, just turn calculation mode back
on when the macro is over with. Try this:
Beginning:
Application.Calculation = False
EXAMPLES:
Sub mySlowMacro()
For x = 2 to 10000
Cells(x,1) = x
Cells(x,2) = x + (x*.10)
Next x
End Sub
Sub myFasterMacro()
Application.ScreenUpdating = False
Application.Calculation = False
For x = 2 to 10000
Cells(x,1) = x
Cells(x,2) = x + (x*.10)
Next x
Application.ScreenUpdating = True
Application.Calculation = True
End Sub
Same deal here: if you’re worksheet needs to re-perform a macro every time a cell is
selected in a worksheet, it may run a gazillion times over the course of a macro
(especially for reports being run). Speed it up by turning off these worksheet or workbook
events. Note: you can’t turn off events in Userforms. You have to get a bit sneakier about
doing that. . .
Beginning:
Application.EnableEvents = False
EXAMPLES:
Sub mySlowMacro()
For x = 2 to 10000
Cells(x,1) = x
Cells(x,2) = x + (x*.10)
Next x
End Sub
Sub myFasterMacro()
Application.ScreenUpdating = False
Application.Calculation = False
Application.EnableEvents = False
For x = 2 to 10000
Cells(x,1) = x
Cells(x,2) = x + (x*.10)
Next x
Application.ScreenUpdating = True
Application.Calculation = True
Application.EnableEvents = True
End Sub
HOT Tip!
If you save your workbook as an “.xlsb” instead of “.xlsm”, it will run faster and take up
less hard drive space. This is a Binary style workbook instead of the regular Macro
Enabled Worksbook. Cool!
View the Video Lesson to speed up your workbook Even more here:
http://www.youtube.com/watch?v=DsJOvT0Fzi4
I hope you find this eBook useful and that it helps you to create
your own extremely cool Excel programs!
Dan, www.excelvbaisfun.com