0% found this document useful (0 votes)
93 views27 pages

Developer Tab - Creating Macros To Simplify Repetitive Tasks in Excel Enabling Macros in Excel

This document discusses macros in Excel and how to create a simple macro to automate repetitive tasks. It begins by defining macros as sequences of commands stored in VB code that can be called upon to repeat tasks. It then explains how to enable macros and set the appropriate security settings in Excel. The document demonstrates how to record a macro to copy data from one sheet to a new sheet, paste the data, and delete certain values. It provides the VB code generated from recording the macro and explains how to edit the code to modify the macro's behavior.

Uploaded by

Lwin Moe Aung
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
93 views27 pages

Developer Tab - Creating Macros To Simplify Repetitive Tasks in Excel Enabling Macros in Excel

This document discusses macros in Excel and how to create a simple macro to automate repetitive tasks. It begins by defining macros as sequences of commands stored in VB code that can be called upon to repeat tasks. It then explains how to enable macros and set the appropriate security settings in Excel. The document demonstrates how to record a macro to copy data from one sheet to a new sheet, paste the data, and delete certain values. It provides the VB code generated from recording the macro and explains how to edit the code to modify the macro's behavior.

Uploaded by

Lwin Moe Aung
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 27

Developer Tab - Creating Macros to simplify repetitive tasks in Excel

Macros are defined by Dictionary.com as : an instruction that represents a sequence of instructions in abbreviated
form. Basically a Macro represents a series of commands that are stored in VB (Visual Basic) code with an Excel
Spreadsheet. These commands may be called upon, and when executed, the Macro code will repeat the
commands on a given spreadsheet.

Here is my definition : Macros are very powerful tools, and can be used to automate a number of tasks within
excel. NOTE: Macros are code. When code is run, it runs exactly as it is told to run. If there are errors in the code,
it may return undesired results. As one client told me, “These Macros are really great. The only thing is they do
what you TELL them to do, not what you THINK they should do.”

Enabling Macros in Excel

By Default, Excel has Macro security set to prompt the user that there are macros contained within the workbook.
You may choose to leave the security settings in the default mode which will prompt for activation / use of the
macro, or you may disable the warnings and allow all macros to run.

Excel 2007 – Office Button – Excel Options – Trust Center – Trust Center Settings – Macro Settings

Excel 2010/2013 – File – Options – Trust Center – Trust Center Settings – Macro Settings

Here we see the options for using Macros in Excel. By Default, the setting is “Disable all macros with notification”.
This selection will prompt the user with a Microsoft Security Warning that there is code enabled in the workbook
that contains a macro. It is up to the user what setting is used. If you are confident that you are not going to
download random Excel Sheets from the internet, you can probably feel safe to use the “Enable all macros” choice.

From the Microsoft web site :

Trust access to the VBA project object model : This setting is for developers and is used to deliberately lock out or
allow programmatic access to the VBA object model from any Automation client. In other words, it provides a
security option for code that is written to automate an Office program and programmatically manipulate the
Microsoft Visual Basic for Applications (VBA) environment and object model. This is a per user and per application
setting, and denies access by default. This security option makes it more difficult for unauthorized programs to
build "self-replicating" code that can harm end-user systems. For any Automation client to be able to access the
VBA object model programmatically, the user running the code must explicitly grant access. To turn on access,
select the check box.
Recording a Macro within a spreadsheet

First, we need to enable the DEVELOPER TAB on the ribbon.

In Excel 2010/2013/365 access FILE – OPTIONS

Select the CUSTOMIZE RIBBON item on the left hand side.

Check the DEVELOPER tab under the Customize the Ribbon / Main Tabs pane.

You should now see the Developer tab in excel.


Creating a Macro :

This example will show a very simple macro to:

- Copy the Contents of an Existing Worksheet


- Create a New Worksheet
- Paste the Contents of an Existing Worksheet into the New Worksheet
- Format the new values within the new Worksheet

Access the Developer Tab in Excel. In the upper left hand corner, you will see the CODE section that contains the
Macro options.

The task is simple, we want to create a macro that will copy the information from the existing sheet, create a new
sheet, paste the information into the new sheet and remove the values from the hours column.

To create the macro, we will use the Record Macro function. NOTE : you are “LIVE” any and all keystrokes that you
perform while recording a macro will be captured. If you make a mistake while recording a macro, it will record the
mistake. When you play the macro back, it will repeat the mistake. This may return undesired results. Take care
to Plan the Work and Work the Plan before attempting to record macros.

Over time, you will develop the ability to look at the code and determine what does and doesn’t belong in the VBA
code. (More on this later).

I have defined the tasks I want to complete at the top of the page.
First, select the option to Record Macro from the Code section of the Developer Tab.

You will be prompted with a dialog box that prompts you to name the macro. The default name is Macro1. You
may change this title, but you may not use special characters or spaces in your Macro Name.

In this example we will call the macro COPY_SHEET. Notice that an underscore is used in lieu of a space.

You may also select a shortcut key to execute the macro – something like Ctrl + “C”…. although this is a shortcut
that is already reserved for “Copy”. You may find it difficult to choose a shortcut key that is already not used.

Store Macro in: In this example, we are storing (or saving) the macro in the current Workbook. If you choose to
store the macro in the PERSONAL workbook, the macro will be available in ALL workbooks that you use. This
feature is a whole other session that we may cover in a future webinar.

Description: This field is used for a brief description of the macro’s use.
As soon as you click “OK” – you are now recording the Macro. Every click and keystroke is being recorded, so take
care to minimize anything moves or clicks that are not part of your task.

The first thing to notice is, when in recording mode, the upper left section of Excel shows “Stop Recording” instead
of “Record Macro”.

First Step:

Highlight all of columns A and B in the spreadsheet. We are highlighting the entire column, not just the available
data range, as this original sheet may have more names added at a later date. We want the macro to capture any
information contained in columns A and B.

We will then right click on the highlighted data range and select COPY. It is important to Right click on the
COLUMN HEADER, and NOT within a cell, as we want to copy the entire contents of the column(s).
Insert a New Worksheet by clicking the icon in the lower left hand corner of the workbook.

Then, access the new worksheet. Right click on cell A1 and select Paste (P).

We will not highlight the values in Column B and delete. We do not want to highligh all of column B, only the
values for the hours. This will require a decision of “how far” you need to go in order to make this usable for future
lists (ie: 30 more employee names added to the original list).
Once the appropriate range is selected, simply press the delete key on the keyboard.

Click on the original sheet (Sheet1) again to finish the macro where it started. Then click the Stop Recording
button. If you get excited, and forget to stop the recording of the Macro, and and all commands from this point on
will still be recorded.

OK – so the macro has been recorded…. Now what?

At this point, I like to save the workbook with the macro intact. If I get undesired results from the macro being run,
I can always revert to the save point BEFORE the macro has been executed.

If you perform the traditional File – Save, you may receive a warning message.

Basically, newer versions of Excel require you to save as a Macro enable workbook. CLICK NO here ! (If you select
“yes”, your macro will be lost.)
Select the option to Save as type: Excel Macro-Enabled Workbook and click SAVE.

This will save the contents of the workbook along with the VB Code that contains the “program” for the Macro.

Test the Macro

In the Upper Left hand corner of the Developer tab, select the button for MACROS.

NOTE : I cannot stress the importance of SAVING YOUR FILE before you run the Macro. You may think that
everything is going to work as planned, but there is NO UNDO for functions created and run by a Macro. If you
save the file BEFORE you run the macro, you can close the file without saving and troubleshoot the code to fix the
undesired results.

You will be shown a list of existing macros within the OPEN WORKBOOKS. If you have other Macro-Enabled
workbooks open, you will see a list of Macros from those workbooks in this window as well.

Take a deep breath and Click RUN.


The screen will flicker as the macro is executed. Look at the results. We have a new sheet with the desired results.

Select Sheet1 and run the macro again. As long as the code is correct, the results will be the same every time.

Viewing the VB Code – troubleshooting macros

We could spend an entire year’s worth of webinars on VB Code. Here are some tips in helping you understand
what we just did. Select the MACRO option from the Developer tab, and choose EDIT.
This will open the VB (Visual Basic) editor. This is the programming code that represents all of the functions that
we just recorded.

You will notice that the code is easy to read, but for the novice, it is difficult to write.

Basically, the code is written to replicate all of the moves we performed while recoding the macro.

Columns("A:B").Select Selects all values in Columns A and B

Selection.Copy Copies the selected range

Sheets.Add After:=Sheets(Sheets.Count) Adds a new worksheet

ActiveSheet.Paste Performs the Paste Function into the new worksheet

Range("B2:B30").Select Selects the desired range B2 – B30

Application.CutCopyMode = False Deactivates the CUT/COPY option because the delete key was
pressed.

Selection.ClearContents Clears the contents of the selected cells

Sheets("Sheet1").Select Selects Sheet1

Range("A1").Select Selects Cell A1


Editing the Code

Just for giggles, let’s make a change to the code. Say we want to change the range of cells that we want to delete
the hours from once the data has been copied. If we want to maintain the Hour values for the first three
employees, we would make the following change(s).

The current code is set to select the values in B2:B30.

We are going to change the code from B2:B30 to B5:B30.

Close the VB editor window and test the macro.

Success. Manually editing macros should be performed with great care, as you may lose functionality with the
macro if you make a coding mistake. It is always a good idea to save the spreadsheet before you make changes.
You may also copy the Macro VB Code out to a Word Document and Paste it back if need be.
Assigning a macro to a BUTTON

Once you are satisfied with the macro and it’s perfomance, you may assign that macro to a button within the
spreadsheet.

Access the Developer tab – select INSERT – Form Controls – Button (Form Control)

This will allow us to create a button and assign the macro to the button. You will first be prompted to “draw” the
size of the button. Click and drag the cursor to create the button shape and size. Release the mouse button.

Select an existing macro – or yo may record a new macro from this step. We will choose the COPY_SHEET macro
that we created earlier.
Right Click on the new button for additional options.

Select Edit Text to Change the text on the button.

Once this is complete, click the button to test the assignment of the macro.
Creating a Macro to format existing data within a spreadsheet.

In this example, we will create a Macro to Format Cells, Adjust Column Width, Delete Unused Column, and insert
header row on the data shown in the following spreadsheet:

In this example, we will save the Macro in our PERSONAL workbook. This allows the macro to be available to us for
use on any and all workbooks that we may open.

We will start by recording the Macro – DEVELOPER TAB, RECORD MACRO.

Give the Macro an appropriate name. You may NOT use spaces when naming macros. In order to get around this,
use the underscore _ instead of spaces.

We will store this Macro in our PERSONAL WORKBOOK. This way, every time we open Excel, this Macro will be
available to us. NOTE: This code is probably not meant for use on all workbooks, only this particualr example.
We can also assign a Shortcut key . Every time we are in Excel, we can fire off the Macro by using the shortcut
keystroke. NOTE : Some shortcut keys are predefined for use within Excel (Such as Ctrl-x for Cut, Ctrl-C for Copy,
Ctrl-v for Paste… etc) You Should NOT overwrite these pre-defined hotkeys, as the Macro hotkey will overwrite the
default hatkey functionality in Excel.

From Microsoft Help article online :

https://support.microsoft.com/kb/212134?wa=wsignin1.0

Using the Assign Macro dialog box in Excel 2000, you can assign a keyboard shortcut to run a macro. The shortcut always uses
the CTRL key in combination with another key on the keyboard. This key must be a letter. Most CTRL+letter combinations
already have specific Excel functionality assigned to them. Assigning a macro to one of those keys overwrites the existing
functionality while the workbook that contains the macro is open. For example, the CTRL+B key combination makes the active
cell contents bold. If you assign the CTRL+B key combination to a macro, the key combination runs the macro instead of
making the cell contents bold.

The following is a list of keys that do not have existing functionality assigned to them when you press the CTRL+letter key
combination:
L
Q
T

The letters E, M, and J are also available, but do have functionality assigned to them in the Microsoft Visual Basic Editor. The
CTRL+E key combination is used to export files. The CTRL+M key combination is used to import files. The CTRL+J key
combination is used to run the Bring To Front command

NOTE: using Ctrl-SHIFT-“letter” is unique, and will not override the hard-coded functions of Excel Hotkeys.

Since Ctrl-f is assigned as the hotkey for FIND/REPLACE in Excel, we will use Ctrl-Shift-F for our FORMAT_CELLS
macro.

Bottom line, if you are going to assign hotkeys to macros, you need to be very, very careful when selecting a
keystroke combination. Using the SHIFT key within your selection will safeguard against overwriting factory
defaults within Excel.
Now on to recording the Macro :

First, we will highlight everything in column C. Right Click on the column header and select delete. Do NOT press
the delete key, this deletes the contents within the cells, it does not delete the selected column.

Next, Highlight the first row, right click and Insert a Row.

Next, Type in Column Headers and bold the text within the headers.
Highlight all of Column A and right click – Format Cells -

Highlight everything in column B – Right Click and select Format Cells.

Finally, we will click in the upper left hand corner to select the entire sheet and doubly click on a line that separates
the column headers to resize all of the columns on the sheet.
If we look at the worksheet in it’s raw form again, we see the Macro is now stored in the PERSONAL!XLSB
workbook, and therefore is available in any and all Workbooks.

This will run the code on any worksheet. In order to EDIT a Macro stored in your PERSONAL workbook, you must
UNHIDE the PERSONAL! Workbook.

From the VIEW tab, Select UNHIDE and choose – PERSONAL.XLSB

You are now in the PERSONAL workbook that sets any and all formatting for new workbooks that are created. You
can change cell size and default font information here, but you need to know that all subsequent Workbooks will
open with te defaults set in the PERSONAL workbook.

If you have saved the Macro in the PERSONAL workbook, you need to save the changes to PERSONAL.XLSB in order
for the macro to be stored properly.
You must also remember to HIDE the personal workbook after you are finished poking around in the VB world.

Form the VIEW tab, select HIDE. If you do not RE-HIDE the PERSONAL.XLSB workbook, every time you open Excel,
instead of being in “Book1.xlsx”, you will be opening the PERSONAL workbook.

Copying and Pasting Existing Code into a Macro.

Start by Recrding a new Macro. DEVELOPER tab, Record Macro. Store the Macro in “this workbook” and click OK.

Immediately Stop Recording the Macro. Click the VISUAL BASIC icon on the DEVELOPER Tab. The blank Macro that
you just recorded will be available here.

If you have Macro text that you procurred from this lesson, or from the internet (caution advised), you can copy
and paste the text from the Macro and overwrite the blank Macro in this screen.
Editing Existing Code (continued)

There is a nice bit of code that is used to eliminate the screen flicker while the macro runs. This code disables the
screen updating. Here is an example of the code.

Sub Macro1()

'

Application.ScreenUpdating = False

'YOUR CODE

Application.ScreenUpdating = True

End Sub

Excel will set screen updating back to True whenever focus is passed back to Excel (your macro finishes) in most
cases, it pays to play it safe and include the code at the end.

Let us edit the Copy_Sheet macro and insert this text within the code.

From the Developer Tab, Choose MACRO – select the appropriate macro – click EDIT.

Type the code into the existing macro – or Copy and Pate the text into the code.

Close the VB editor and test the macro. You will notice that the code now runs without skipping through the process
of executing the commands visually. This is a great way to speed up the execution of macros.
Here is an exampe of a Macro that includes :

- Protecting / Unprotecting Sheets (with password)

- Hiding / Unhiding Sheets

- Refreshing Queries

- Refreshing Pivot Tables

- Filtering out 0.00 values from a table

Sub Macro1()

'

' Macro1 Macro

' Stops screen updating while macro runs (will not show sheet unhide / hide)

Application.ScreenUpdating = False

' Unprotects REPORT Sheet

Sheets("REPORT").Unprotect Password:="XXXYYY"

' Unhides worksheet to refresh

Sheets("JOBS").Visible = True

Sheets("JC DATA").Visible = True

Sheets("BUDGET").Visible = True

Sheets("CO").Visible = True

Sheets("PIVOT").Visible = True

' Refreshes Queries

Sheets("CO").Select

Range("A1").Select

Selection.ListObject.QueryTable.Refresh BackgroundQuery:=False

Sheets("BUDGET").Select

Range("A1").Select

Selection.ListObject.QueryTable.Refresh BackgroundQuery:=False

Sheets("JC DATA").Select

Range("A1").Select

Selection.ListObject.QueryTable.Refresh BackgroundQuery:=False

Sheets("PIVOT").Select
Range("A4").Select

ActiveSheet.PivotTables("PivotTable1").PivotCache.Refresh

' Hides worksheets

Sheets("JOBS").Visible = False

Sheets("JC DATA").Visible = False

Sheets("BUDGET").Visible = False

Sheets("CO").Visible = False

Sheets("PIVOT").Visible = False

' Unhides all Rows in MasterTable

Sheets("REPORT").Select

ActiveSheet.ListObjects("Table2").Range.AutoFilter Field:=8

Range("A5").Select

' Filters out all rows with 0.00 value in TOTAL column

ActiveSheet.Range("$A$7:$M$705").AutoFilter Field:=8, Criteria1:="<>0", Operator:=xlFilterValues

' Protects REPORT sheet with password

Sheets("REPORT").Protect Password:="XXXYYY"

End Sub

NOTES ON MACROS :

- Something as innocent as renaming a sheet can cause a macro to fail. When created, a macro is very
specific to select certain worksheets within a workbook. If you change the name of a worksheet on a
particular workbook, the code will lose reference to the original name, and break.

- Google is your friend. You can use Google searches to find almost anything. Use a search string that
includes “MACRO” at the end of whatever you are looking for. For example: “Hide specific worksheets
macro”, “Rename sheets based on cell value MACRO” or “find last row MACRO”. The search results
will take you to a number of websites and message boards with people who have the same problem(s).
Of course, use caution when using code written by somebody else. Review the code and “make it
yours”.

- Get to know the basics of VB Code – you don’t necessarily have to know how to WRITE the code, but
understanding the code will help with creating extremely effective macros.

- Keep in mind that the ORDER in which items are recorded may cause problems. If a macro is not
working, try switching the order in which the macro is recorded.

- For larger projects, try to record smaller portions of the macro. Run the small parts and paste the
macro together in pieces, testing the results as you go along.
Sub Macro3()
' Refreshes Queries and Pivot Tables individually within workbooks

' Macro3 Macro

'

Application.ScreenUpdating = False

' Refreshes Queries

Sheets("JOB").Select

Range("A1").Select

Selection.ListObject.QueryTable.Refresh BackgroundQuery:=False

Sheets("EMPLOYEES").Select

Range("A1").Select

Selection.ListObject.QueryTable.Refresh BackgroundQuery:=False

Sheets("TCHIS").Select

Range("A1").Select

Selection.ListObject.QueryTable.Refresh BackgroundQuery:=False

Sheets("REPORT").Select

Range("A3").Select

' Refreshes Pivot Table

ActiveSheet.PivotTables("PivotTable1").PivotCache.Refresh

Range("A1").Select

' Creates a new Tab for Every Date in Pivot Table

ActiveSheet.PivotTables("PivotTable1").ShowPages PageField:="CHECK DATE"

Range("D1").Select
' Renames New Sheets as Date in Cell B1

Dim sh

For Each sh In ActiveWorkbook.Worksheets

If IsDate(sh.Range("B1")) Then

sh.Name = Format(sh.Range("B1").Value, "MM-DD-YY")

Else

sh.Name = sh.Name

End If

Next sh

' Autosize all Worksheets Workbook

Dim wkSt As String

Dim wkBk As Worksheet

wkSt = ActiveSheet.Name

For Each wkBk In ActiveWorkbook.Worksheets

On Error Resume Next

wkBk.Activate

Cells.EntireColumn.AutoFit

Next wkBk

Sheets(wkSt).Select

Application.ScreenUpdating = True

End Sub
Sub Delete_Sheets()
' Deletes all sheets except for those named in the code

Dim s

Application.DisplayAlerts = False

For Each s In Sheets

If s.Name <> "Date" And s.Name <> "REPORT" And _

s.Name <> "TCHIS" And s.Name <> "EMPLOYEES" And _

s.Name <> "JOB" Then

s.Delete

End If

Next

Application.DisplayAlerts = True

'

End Sub
CODE TO SAVE EXCEL FILE AS .PDF, OPEN OUTLOOK, ATTACH FILE TO EMAIL:

From this thread on MrExcel :

http://www.mrexcel.com/forum/excel-questions/710212-visual-basic-applications-code-convert-excel-
pdf-email-attachment-2.html

Sub AttachActiveSheetPDF_01()

Dim IsCreated As Boolean

Dim PdfFile As String, Title As String

Dim OutlApp As Object

' Not sure for what the Title is

Title = Range("A1")

' Define PDF filename

Title = "Request Form for " & Range("A1").Value

PdfFile = CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\" & Title & ".pdf"

' Export activesheet as PDF

With ActiveSheet

.ExportAsFixedFormat Type:=xlTypePDF, Filename:=PdfFile, Quality:=xlQualityStandard,


IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False

End With

' Use already open Outlook if possible

On Error Resume Next

Set OutlApp = GetObject(, "Outlook.Application")

If Err Then

Set OutlApp = CreateObject("Outlook.Application")

IsCreated = True
End If

OutlApp.Visible = True

On Error GoTo 0

' Prepare e-mail with PDF attachment

With OutlApp.CreateItem(0)

' Prepare e-mail

.Subject = Title

.To = "..." ' <-- Put email of the recipient here

.CC = "..." ' <-- Put email of 'copy to' recipient here

.Body = "Hi," & vbLf & vbLf _

& "See the attached requiest in PDF format." & vbLf & vbLf _

& "Regards," & vbLf _

& Application.UserName & vbLf & vbLf

.Attachments.Add PdfFile

' Try to send

Application.Visible = True

.Display

End With

' Quit Outlook if it was not already open

If IsCreated Then OutlApp.Quit

' Release the memory of object variable

Set OutlApp = Nothing

End Sub

You might also like