Quantcast
Channel: An Excel Blog For The Real World
Viewing all 117 articles
Browse latest View live

Automate Building A Table Of Contents For Your Spreadsheet With VBA

$
0
0
Creating a Spreadsheet with Table of Contents VBA code automate

Managing Large Workbooks

I've been working with a bunch of rather large Excel workbooks lately and it has come to the point where it is more efficient to navigate through a table of contents page rather than scrolling through the tabs themselves. One of my very first products after first launching this website back in 2014 was a template called the Tab Filter. I created this template to show how you could use VBA and some buttons to narrow down the visible tabs in a workbook.  For example, you could click on the 1995 button and only tabs with names containing "1995" would be left visible in the workbook.  This template is still available today and you can pick it up for free (or if you're feeling generous, you can make a donation payment along with download).

However, with my more recent situation, I'm pulling together a bunch of different reports that aren't really named in a nomenclature that can be narrowed down logically.  I found that a table of contents worksheet with hyperlinks directly to my tabs was much more efficient, but also a real pain to create.  Luckily, I know a thing or two about writing VBA code, so I whipped up a macro that could create a table of contents worksheet in seconds!

A VBA Macro To Automatically Insert A Table Of Contents Page

This code is very straightforward in its functionality.  It looks for a worksheet named "Contents" and if it already exists in the workbook, it asks to delete it.  Next, it inserts a new worksheet called "Contents" and gets to work creating hyperlinks to all the tabs in your Excel file.  Finally, I added a section that formats the Contents worksheet so it's pleasing to the eye (or at least to my eye).  You can stick this VBA code into your Personal Macros file and whip it out when your situation calls for it and create practical table of contents pages in seconds!

VBA macro code to create a workbook table of contents with links

Here's the VBA Code

Sub TableOfContents_Create()
'PURPOSE: Add a Table of Contents worksheets to easily navigate to any tab
'SOURCE: www.TheSpreadsheetGuru.com

Dim sht As Worksheet
Dim Content_sht As Worksheet
Dim myArray As Variant
Dim x As Long, y As Long
Dim shtName1 As String, shtName2 As String
Dim ContentName As String

'Inputs
  ContentName = "Contents"

'Optimize Code
  Application.DisplayAlerts = False
  Application.ScreenUpdating = False

'Delete Contents Sheet if it already exists
  On Error Resume Next
    Worksheets("Contents").Activate
  On Error GoTo 0

  If ActiveSheet.Name = ContentName Then
    myAnswer = MsgBox("A worksheet named [" & ContentName & _
      "] has already been created, would you like to replace it?", vbYesNo)
    
    'Did user select No or Cancel?
      If myAnswer <> vbYes Then GoTo ExitSub
      
    'Delete old Contents Tab
      Worksheets(ContentName).Delete
  End If

'Create New Contents Sheet
  Worksheets.Add Before:=Worksheets(1)

'Set variable to Contents Sheet
  Set Content_sht = ActiveSheet

'Format Contents Sheet
  With Content_sht
    .Name = ContentName
    .Range("B1") = "Table of Contents"
    .Range("B1").Font.Bold = True
  End With

'Create Array list with sheet names (excluding Contents)
  ReDim myArray(1 To Worksheets.Count - 1)

  For Each sht In ActiveWorkbook.Worksheets
    If sht.Name <> ContentName Then
      myArray(x + 1) = sht.Name
      x = x + 1
    End If
  Next sht
  
'Alphabetize Sheet Names in Array List
  For x = LBound(myArray) To UBound(myArray)
    For y = x To UBound(myArray)
      If UCase(myArray(y)) < UCase(myArray(x)) Then
        shtName1 = myArray(x)
        shtName2 = myArray(y)
        myArray(x) = shtName2
        myArray(y) = shtName1
      End If
     Next y
  Next x

'Create Table of Contents
  For x = LBound(myArray) To UBound(myArray)
    Set sht = Worksheets(myArray(x))
    sht.Activate
    With Content_sht
      .Hyperlinks.Add .Cells(x + 2, 3), "", _
      SubAddress:="'" & sht.Name & "'!A1", _
      TextToDisplay:=sht.Name
      .Cells(x + 2, 2).Value = x
    End With
  Next x
  
Content_sht.Activate
Content_sht.Columns(3).EntireColumn.AutoFit

'A Splash of Guru Formatting! [Optional]
  Columns("A:B").ColumnWidth = 3.86
  Range("B1").Font.Size = 18
  Range("B1:F1").Borders(xlEdgeBottom).Weight = xlThin
  
  With Range("B3:B" & x + 1)
    .Borders(xlInsideHorizontal).Color = RGB(255, 255, 255)
    .Borders(xlInsideHorizontal).Weight = xlMedium
    .HorizontalAlignment = xlCenter
    .VerticalAlignment = xlCenter
    .Font.Color = RGB(255, 255, 255)
    .Interior.Color = RGB(91, 155, 213)
  End With

  'Adjust Zoom and Remove Gridlines
    ActiveWindow.DisplayGridlines = False
    ActiveWindow.Zoom = 130

ExitSub:
'Optimize Code
  Application.DisplayAlerts = True
  Application.ScreenUpdating = True
  
End Sub

Limiting The Lines Per Column

In the event you have an extremely large amount of tabs in your Excel workbook, you may want multiple columns of hyperlinks.  To handle these situations, I tweaked the code a little bit to let the user decide how many columns to have in the Table of Contents.  Take a look at how I can now fit the 50 states easily in a much more condensed format.

Create a mutli-line table of contents in Microsoft Excel

Here's The VBA Code

Sub TableOfContents_Create()
'PURPOSE: Add a Table of Contents worksheets to easily navigate to any tab (multiple columns)
'SOURCE: www.TheSpreadsheetGuru.com

Dim sht As Worksheet
Dim Content_sht As Worksheet
Dim myArray As Variant
Dim x As Long, y As Long, z As Long
Dim shtName1 As String, shtName2 As String
Dim ContentName As String
Dim shtCount As Long
Dim ColumnCount As Variant

'Inputs
  ContentName = "Contents"

'Optimize Code
  Application.DisplayAlerts = False
  Application.ScreenUpdating = False

'Delete Contents Sheet if it already exists
  On Error Resume Next
    Worksheets("Contents").Activate
  On Error GoTo 0

  If ActiveSheet.Name = ContentName Then
    myAnswer = MsgBox("A worksheet named [" & ContentName & _
      "] has already been created, would you like to replace it?", vbYesNo)
    
    'Did user select No or Cancel?
      If myAnswer <> vbYes Then GoTo ExitSub
      
    'Delete old Contents Tab
      Worksheets(ContentName).Delete
  End If

'Count how many Visible sheets there are
  For Each sht In ActiveWorkbook.Worksheets
    If sht.Visible = True Then shtCount = shtCount + 1
  Next sht

'Ask how many columns to have
  ColumnCount = Application.InputBox("You have " & shtCount & _
    " visible worksheets." & vbNewLine & "How many columns " & _
    "would you like to have in your Contents tab?", Type:=2)

'Check if user cancelled
  If TypeName(ColumnCount) = "Boolean" Or ColumnCount < 0 Then GoTo ExitSub

'Create New Contents Sheet
  Worksheets.Add Before:=Worksheets(1)

'Set variable to Contents Sheet and Rename
  Set Content_sht = ActiveSheet
  Content_sht.Name = ContentName
  
'Create Array list with sheet names (excluding Contents)
  ReDim myArray(1 To shtCount)

  For Each sht In ActiveWorkbook.Worksheets
    If sht.Name <> ContentName And sht.Visible = True Then
      myArray(x + 1) = sht.Name
      x = x + 1
    End If
  Next sht
  
'Alphabetize Sheet Names in Array List
  For x = LBound(myArray) To UBound(myArray)
    For y = x To UBound(myArray)
      If UCase(myArray(y)) < UCase(myArray(x)) Then
        shtName1 = myArray(x)
        shtName2 = myArray(y)
        myArray(x) = shtName2
        myArray(y) = shtName1
      End If
     Next y
  Next x

'Create Table of Contents
  x = 1

  For y = 1 To ColumnCount
    For z = 1 To WorksheetFunction.RoundUp(shtCount / ColumnCount, 0)
      If x <= UBound(myArray) Then
        Set sht = Worksheets(myArray(x))
        sht.Activate
        With Content_sht
          .Hyperlinks.Add .Cells(z + 2, 2 * y), "", _
          SubAddress:="'" & sht.Name & "'!A1", _
          TextToDisplay:=sht.Name
        End With
        x = x + 1
      End If
    Next z
  Next y

'Select Content Sheet and clean up a little bit
  Content_sht.Activate
  Content_sht.UsedRange.EntireColumn.AutoFit
  ActiveWindow.DisplayGridlines = False

'Format Contents Sheet Title
  With Content_sht.Range("B1")
    .Value = "Table of Contents"
    .Font.Bold = True
    .Font.Size = 18
  End With

ExitSub:
'Optimize Code
  Application.DisplayAlerts = True
  Application.ScreenUpdating = True
  
End Sub

Adding Hyperlinks Back To Your Table of Contents

If you want to have a way to easily navigate back to your Contents tab, you may want to add this snippet of VBA code to your Table of Contents macro. This code will add a button near cell A1 of every worksheet with a hyperlink back to your contents page. I decided to use a button that sits on top of the spreadsheet instead of using an in-cell hyperlink to bypass the chance of overriding any data that might be sitting in cell A1. You can run this as a separate macro or copy & paste it (do NOT include the "Sub" statements) into either of the above routines to carry out a "one and done" execution.

I want to give a special thanks to Jim F. (via email) for suggesting this feature. Great idea!

Sub Contents_Hyperlinks()
'PURPOSE: Add hyperlinked buttons back to Table of Contents worksheet tab

Dim sht As Worksheet
Dim myShape As Shape
Dim ContentName As String

'Inputs - Table of Contents Worksheet Name
  ContentName = "Contents"
  
'Loop Through Each Worksheet in Workbook
  For Each sht In ActiveWorkbook.Worksheets
    If sht.Name <> ContentName Then
  
      'Create & Position Shape
        Set myShape = sht.Shapes.AddShape(msoShapeRoundedRectangle, _
          4, 4, 60, 20)

      'Format Shape
        myShape.Fill.ForeColor.RGB = RGB(91, 155, 213) 'Blue
        myShape.Line.Visible = msoFalse
        myShape.TextFrame2.TextRange.Font.Size = 10
        myShape.TextFrame2.TextRange.Text = ContentName
        myShape.TextFrame2.TextRange.Font.Bold = True
        myShape.TextFrame2.TextRange.Font.Fill.ForeColor.RGB = RGB(255, 255, 255) 'White
      
      'Assign Hyperlink to Shape
        sht.Hyperlinks.Add myShape, "", _
          SubAddress:="'" & ContentName & "'!A1"
  
   End If
  Next sht

End Sub

Learn More With This Example Workbook

I have created a sample workbook with 4 different variations of VBA code for creating table of contents for your Excel workbook. The workbook and its code are completely unlocked so you can dig in and discover how the magic works. As always, in order to download this example file you will need to be a subscriber of my free newsletter.  If you click the green button below you can easily sign up and you will be emailed the password to get into the subscribers-only area of this website.

       Already Subscribed? Click HERE to log-in to the "Example Files" section

     Already Subscribed? Click HERE to log-in to the "Example Files" section

 

Workbook Navigation Made Easier

Hopefully, after running one of the two macros I created in this article you are able to navigate your workbook much more efficiently. I'm curious if there would be other features or formatting techniques that you would recommend to improve this code.  Leave your thoughts in the comments section below as I'd love to hear from you and pick your brain a little bit.

How Do I Modify This To Fit My Specific Needs?

Chances are this post did not give you the exact answer you were looking for. We all have different situations and it's impossible to account for every particular need one might have. That's why I want to share with you: My Guide to Getting the Solution to your Problems FAST! In this article, I explain the best strategies I have come up with over the years to getting quick answers to complex problems in Excel, PowerPoint, VBA, you name it

I highly recommend that you check this guide out before asking me or anyone else in the comments section to solve your specific problem. I can guarantee 9 times out of 10, one of my strategies will get you the answer(s) you are needing faster than it will take me to get back to you with a possible solution. I try my best to help everyone out, but sometimes I don't have time to fit everyone's questions in (there never seem to be quite enough hours in the day!).

I wish you the best of luck and I hope this tutorial gets you heading in the right direction!

Chris "Macro" Newman :)


How To Repeat Tasks With Your VBA Code by Looping

$
0
0
VBA Coding Looping Statements Repeat Tasks

Your Complete Looping Guide

Looping is extremely important when coding because it can shorten up the length of your code tremendously.  It's kind of like having a macro inside your macro since it allows you to repeat the same task (or apply the same action) over and over and over again.  Each looping statement has an opening line and a closing line; a beginning and an end if you will.  You will want to insert your repeatable action in between the opening and closing lines of the statement so your code keeps getting repeated. Let's start with the basics and cover the three major ways to loop.

For Loop

This type of loop is great for cycling through a pre-determined number of times.  The loop needs to begin with the word "For" and then a variable name followed by an equals sign (=) and finally the range from which you want your variable to equal during the loop (ie 15 to 25 or 1 to 5). The below example code will write a given phrase into the Immediate Window one hundred times.

Sub For_Loop()

Dim x As Long

'Write "I will not chew gum in class" 100 times
  For x = 1 To 100
    Debug.Print x & ". I will not chew gum in class."
  Next x

End Sub

For Each Loop

The For Each looping method is meant for cycling through objects on your spreadsheet.  This loop can handle anything from cells to charts. The key to this loop is making sure the loop knows which type of object to look for.  For example, if I want to loop through Pivot Tables in Sheet1, I'm going to want to tell the For Each loop to look "in" Worksheets("Sheet1").PivotTables. Most of the time, your object type is going to end in an "s". So you would NOT want to write Worksheets("Sheet1").PivotTable. This can be pretty tricky at first, so I've provided an example below and a TON of examples in the next section. Eventually, they will become second nature to you so don't give up on using them!

Sub ForEach_Loop()

Dim cell As Range

'How many cells in worksheet have values in them?
  For Each cell In ActiveSheet.UsedRange.Cells
    If cell.Value <> "" Then x = x + 1
  Next cell

'Report out results
  MsgBox "There are " & x & " cells containing data in you worksheet"

End Sub

Do While Loop

A Do While loop is probably the lesser known of the looping methods out there, but it can be very useful in certain situations.  Basically, the loop keeps cycling through until a logical test is failed (returns a false). In the below example, the Do While loop will keep on iterating until the variable BlankFound = True.

Sub DoWhile_Loop()

Dim BlankFound As Boolean
Dim x As Long

'Loop until a blank cell is found in Column A
  Do While BlankFound = False
    x = x + 1
    
    If Cells(x, "A").Value = "" Then
      BlankFound = True
    End If
  Loop

'Report out first blank cell found in Column A
  MsgBox "Cell A" & x & " is blank!"
  
End Sub

BE VERY CAREFUL! If your Do While loop never fails its test your loop will go on forever.  This may be good for a practical joke, but not for an automation macro. So make sure if you use this loop it is guaranteed to break its logical test at some point during your code's execution.

Loop Example VBA Code

My personal favorite method of looping would definitely be the For Each loop and because it can be a little confusing when you are first teaching yourself the awesome skill that is looping, I wanted to provide you with a ton of examples of different ways you can cycle through objects in your Excel files.  So without further ado, here is my "brain-dump" of loops to get you started!

** All the example code below is outputting names of the objects being looped into the Immediate Window (ie Debug.Print).  You can see what's being generated by displaying the Immediate Window with the shortcut Ctrl + g inside the Visual Basic Editor.

Looping Through Workbooks

Sub Workbook_Loop()

Dim wb As Workbook

'Loop through each open Excel Workbook
  For Each wb In Application.Workbooks
    Debug.Print wb.Name
  Next Workbook

End Sub

Looping Through Worksheets

Sub Worksheet_Loop()

Dim sht As Worksheet

'Loop through each worksheet in a workbook
  For Each sht In ThisWorkbook.Worksheets
    Debug.Print sht.Name
  Next sht

End Sub

Looping Through Cells

Sub Cell_Loop()

Dim cell As Range

'Loop through each cell in a cell range
  For Each cell In ActiveSheet.Range("A1:Z100")
    Debug.Print cell.Value
  Next cell

'Loop through each cell in a Named Range
  For Each cell In ActiveSheet.Range("RawData")
    Debug.Print cell.Value
  Next cell

'Loop through each cell in a Table body range
  For Each cell In ActiveSheet.ListObjects("Table1").DataBodyRange
    Debug.Print cell.Value
  Next cell

End Sub

Looping Through Charts

Sub Chart_Loop()

Dim sht As Worksheet
Dim cht As ChartObject

'Loop through each chart in the active workbook
  For Each sht In ActiveWorkbook.Worksheets
    For Each cht In sht.ChartObjects
      Debug.Print cht.Name
    Next cht
  Next sht

End Sub

Looping Through Shapes

Sub Shape_Loop()

Dim sht As Worksheet
Dim shp As Shape

'Loop through each shape in the active workbook
  For Each sht In ActiveWorkbook.Worksheets
    For Each shp In sht.Shapes
      If shp.Type = msoAutoShape Then
        Debug.Print shp.Name
      End If
    Next shp
  Next sht

End Sub

Looping Through Pivot Tables

Sub PivotTable_Loop()

Dim sht As Worksheet
Dim pvt As PivotTable

'Loop through each pivot table in the active workbook
  For Each sht In ActiveWorkbook.Worksheets
    For Each pvt In sht.PivotTables
      Debug.Print pvt.Name
    Next pvt
  Next sht

End Sub

Looping Through Tables

Sub Table_Loop()

Dim sht As Worksheet
Dim tbl As ListObject

'Loop through each table in the active workbook
  For Each sht In ActiveWorkbook.Worksheets
    For Each tbl In sht.ListObjects
      Debug.Print tbl.Name
    Next tbl
  Next sht

End Sub

Looping Through Array Items

Sub Array_Loop()

Dim myArray As Variant
Dim x As Long

'Fill your Array with data
  myArray = Array("OH", "GA", "FL", "TX")

'Loop through each item in an Array list
  For x = LBound(myArray) To UBound(myArray)
    Debug.Print myArray(x)
  Next x

End Sub

Looping Backwards Through Array Items

Sub Array_LoopBackwards()

Dim myArray As Variant
Dim x As Long

'Fill your Array with data
  myArray = Array("OH", "GA", "FL", "TX")

'Loop backwords through each item in an Array list
  For x = UBound(myArray) To LBound(myArray) Step -1
    Debug.Print myArray(x)
  Next x

End Sub

Looping Through Combo Boxes (Form Control

Sub ComboBox_FormControl_Loop()

Dim cmbo As Shape

'Loop through each Form Control Combo Box in ActiveSheet
  For Each cmbo In ActiveSheet.Shapes
    If cmbo.Type = msoFormControl And cmbo.FormControlType = xlDropDown Then
      Debug.Print cmbo.Name
    End If
  Next cmbo

End Sub

Looping Through Checkboxes (Form Control)

Sub CheckBox_FormControl_Loop()

Dim cb As Shape

'Loop through each Form Control Checkbox in ActiveSheet
  For Each cb In ActiveSheet.Shapes
    If cb.Type = msoFormControl And cb.FormControlType = xlCheckBox Then
      Debug.Print cb.Name
    End If
  Next cb

End Sub

Looping Through Option Buttons (Form Control)

Sub OptionButton_FormControl_Loop()

Dim OptBtn As Shape

'Loop through each Form Control Checkbox in ActiveSheet
  For Each OptBtn In ActiveSheet.Shapes
    If OptBtn.Type = msoFormControl And OptBtn.FormControlType = xlOptionButton Then
      Debug.Print OptBtn.Name
    End If
  Next OptBtn

End Sub

Looping Through Buttons (Form Control)

Sub Button_FormControl_Loop()

Dim btn As Shape

'Loop through each Form Control Button in ActiveSheet
  For Each btn In ActiveSheet.Shapes
    If btn.Type = msoFormControl And btn.FormControlType = xlButtonControl Then
      Debug.Print btn.Name
    End If
  Next btn

End Sub

Looping Through CheckBoxes (ActiveX)

Sub CheckBox_ActiveX_Loop()

Dim cb As OLEObject

'Loop through each ActiveX Control CheckBox in ActiveSheet
  For Each cb In ActiveSheet.OLEObjects
    If TypeName(cb.Object) = "CheckBox" Then
      Debug.Print cb.Name
    End If
  Next cb

End Sub

Looping Through Combo Boxes (ActiveX)

Sub ComboBox_ActiveX_Loop()

Dim cmbo As OLEObject

'Loop through each ActiveX Control Combo Box in ActiveSheet
  For Each cmbo In ActiveSheet.OLEObjects
    If TypeName(cmbo.Object) = "ComboBox" Then
      Debug.Print cmbo.Name
    End If
  Next cmbo

End Sub

Looping Through Option Buttons (ActiveX)

Sub OptionButton_ActiveX_Loop()

Dim optn As OLEObject

'Loop through each ActiveX Control Option Button in ActiveSheet
  For Each optn In ActiveSheet.OLEObjects
    If TypeName(optn.Object) = "OptionButton" Then
      Debug.Print optn.Name
    End If
  Next optn

End Sub

Looping Through Textboxes (ActiveX)

Sub TextBox_ActiveX_Loop()

Dim txtbx As OLEObject

'Loop through each ActiveX Control TextBox in ActiveSheet
  For Each txtbx In ActiveSheet.OLEObjects
    If TypeName(txtbx.Object) = "TextBox" Then
      Debug.Print txtbx.Name
    End If
  Next txtbx

End Sub

Looping Through Command Buttons (ActiveX)

Sub CommandButton_ActiveX_Loop()

Dim btn As OLEObject

'Loop through each ActiveX Control Command Button in ActiveSheet
  For Each btn In ActiveSheet.OLEObjects
    If TypeName(btn.Object) = "CommandButton" Then
      Debug.Print btn.Name
    End If
  Next btn

End Sub

Looping Through Toggle Buttons (ActiveX)

Sub ToggleButton_ActiveX_Loop()

Dim tggl As OLEObject

'Loop through each ActiveX Control Toggle Button in ActiveSheet
  For Each tggl In ActiveSheet.OLEObjects
    If TypeName(tggl.Object) = "ToggleButton" Then
      Debug.Print tggl.Name
    End If
  Next tggl

End Sub

More Looping Articles You Might Enjoy

Whew! That Was A Lot Of Examples!!

I warned you it was a brain dump! I'm sure you didn't need to absorb every example on this page, but hopefully I was able to get you to the loop you were trying to figure out.  If I missed something you were looking for, feel free to drop a note in the comments section and I'll see if I can help you with your looping question. Thanks for stoping by!


How Do I Modify This To Fit My Specific Needs?

Chances are this post did not give you the exact answer you were looking for. We all have different situations and it's impossible to account for every particular need one might have. That's why I want to share with you: My Guide to Getting the Solution to your Problems FAST! In this article, I explain the best strategies I have come up with over the years to getting quick answers to complex problems in Excel, PowerPoint, VBA, you name it

I highly recommend that you check this guide out before asking me or anyone else in the comments section to solve your specific problem. I can guarantee 9 times out of 10, one of my strategies will get you the answer(s) you are needing faster than it will take me to get back to you with a possible solution. I try my best to help everyone out, but sometimes I don't have time to fit everyone's questions in (there never seem to be quite enough hours in the day!).

I wish you the best of luck and I hope this tutorial gets you heading in the right direction!

Chris "Macro" Newman :)

Best Way To Paste Special Excel Objects As PowerPoint Images

$
0
0
Differences Between Paste Special Options Between Excel And PowerPoint

Quality Matters

I've written many times in the past on how the quality and formatting of your work can separate you from the rest of the pack when creating presentations. Our cultural is becoming more and more focused on graphic design and it has been proven to increase your audience's ability to understand the data you are presenting. 

As a financial analyst, I spend quite a bit of time preparing presentations for executives and board of directors and I don't want to send them slides with charts that are hard to read because they are too blurry. If you have ever copied an Excel object over to PowerPoint as an image you probably noticed that Microsoft offers you a ton of formats to pick from in the Paste Special dialog box.

What does all this mean? Which one do I pick?

What does all this mean? Which one do I pick?

All these choices can be confusing and maybe a little bit frightening! What's the difference between all these formats and are there certain situations where I would want to pick one over the other? Well, those two questions are what I intend to answer for you in the post. Let's first get acquainted with what some of these image types are.

Breakdown Of The Most Common Types

Breakdown of Most Common Types of Image Formats in Excel

JPEG (Joint Photographic Experts Group)

This format is best for realistic images that blend and have shadows (ie a picture you took with your camera). JPEG supports 24-bit colors and the level of compression can be increased or decreased depending on the capabilities of the software you are using. Transparent backgrounds are not supported by this format and any transparency is typically converted to the color white.

GIF (Graphics Interchange Format)

This is an old school format and is best to use with images that have just a few colors with no color fades (blending). Simple cartoons and icons are good examples of images that would be better off saved as a GIF instead of a JPEG. This format is typically not used anymore unless you are wanting an animated image (aka animated GIF) or are needing the format for compatibility reasons with old software.

PNG (Portable Network Graphic)

Pronounced "ping", this format was a spin-off of the GIF format. This file type can contain thousands of colors and has a better compression algorithm than a GIF. Portable Network Graphics also allow for a transparent background, making this format great for icons.

BMP (Bitmap)

This file format can take up a lot of memory and disk space, but is exactly as you see on the screen. If file size is not an issue and you want great on-screen quality, this would be the file type you would want to go with.

WMF (Windows Metafile)

This file format was created to work with Microsoft Windows and works well with MS Office. It supports 16-bit color but was left to the wind when Microsoft created the 32-bit color format called Enhanced Metafile.

EMF (Enhanced Metafile)

This is the new and improved version of the WMF format as it supports 32-bit color. Microsoft says this format is better than Bitmap for printing to high-quality printers, but the on-screen image will appear slightly modified. Enhanced Metafiles have a smaller file size and MS Office can redraw (process) it faster when comparing with a Windows Metafile image.

Microsoft Office Drawing Object

This format was exclusively made for Microsoft Office as it inserts the contents of the Clipboard as an Office object that can be edited and reformatted as if you had created it yourself.

So Which One Should I Use?

I've done quite a bit of testing in Excel and PowerPoint to see which Paste Special format I should be using to create my presentations. Below are my recommendations. Please note that my testing was only for on-screen quality. Microsoft claims that the Enhanced Metafile format will give you the highest quality while printing to paper.

Ranges, Tables, & Pivot Tables

While copying over ranges into PowerPoint, you are much more limited in the paste special types. Because of this, I only tested the Enhanced Metafile and Bitmap formats. The Enhanced Metafile format had a much better image quality than the Bitmap on-screen.

Click to enlarge

Click to enlarge

Charts and Charts Grouped With Shapes

Charts are probably the main Excel objects that you might be pasting over into a PowerPoint presentation. Through my testing, the PNG and Bitmap file formats had a much higher quality than the Enhanced Metafile. I would recommend using the PNG format due to its transparent background. 

Click to enlarge

Click to enlarge

Shapes, Text boxes, & Grouped Shapes

When you paste any form of shape (including text boxes) into PowerPoint, the Enhanced Metafile beats out all the rest and it has a transparent background so it is the clear winner!

Click to enlarge

Click to enlarge

Here's What You Need To Know

In summation, I would recommend using the PNG format for anything with charts in them and Enhanced Metafiles for everything else. I performed my tests using Windows 8.1 and Office 2013, so I don't know if different version combinations have different results. But nevertheless, I found the results very interesting! Let me know in the comments below how you typically paste your Excel data into PowerPoint and if this article will change your process going forward.

If you want an in-depth overview of the various image file formats, you can check out Microsoft's guidelines for selecting the appropriate picture format in an Office program.


Check out my brand new Excel add-in that allows you to automate creating your monthly PowerPoint slides!

Check out my brand new Excel add-in that allows you to automate creating your monthly PowerPoint slides!

How to Install and Uninstall A VBA Add-in File For Microsoft Office

$
0
0
How To Setup and Install an Add-in File for Excel

Installing Your Add-in

So you just purchased a shiny, brand-new add-in program to take your Office capabilities to the next level. The only problem is, there isn't an executable installer to put it on your computer! Let's walk through the steps to get your add-in file up and running in no time.

Note: I will be using Microsoft Excel for this demonstration, but the rest of the Office programs should have very similar processes.

A. Save Your File To Your Computer

You can save your add-in file anywhere you wish, but I recommend you save it in the default add-in folder for Office. This folder location varies based on which operating system you are using.

Windows XP 

C:\Documents and Settings\[insert your username]\Application Data\Microsoft\AddIns

Windows Vista / Windows 7 / Windows 8 

C:\Users\[insert your username]\AppData\Roaming\Microsoft\AddIns

B. Telling Office Where Your Add-in File Is

The Quick Way (Excel 2010 and later)

  1. Go to the Developer tab
  2. Click the Add-ins Button
  3. Inside the Add-ins Dialog Box, click the Browse… button
  4. The Explorer Window should default to the Microsoft add-in folder location
  5. Navigate and select your add-in file, then click OK
  6. Ensure the newly added add-in name is checked in the dialog's listbox & click OK
  7. Your add-in is now installed!
Installing an Microsoft Excel add-in file

The Slightly Longer Way (Excel 2007 and later)

  1. Go to File inside your Excel Program
  2. Select Excel Options
  3. Select Add-ins from the left-hand pane
  4. Make sure Excel Add-ins is chosen in the Manage drop-down menu and click Go…
  5. Inside the Add-ins Dialog Box, click the Browse… button
  6. The Explorer Window should default to the Microsoft add-in folder location
  7. Navigate and select your add-in file, then click OK
  8. Ensure the newly added add-in name is checked in the dialog's listbox & click OK
  9. Your add-in is now installed!
Installing an Microsoft Excel add-in file

C. Unloading An Add-in

If you want to stop using a particular add-in for a temporary period of time, you can navigate back to the Add-ins dialog box and simply uncheck the add-in's name, then click OK. The add-in will disappear from your current session and also will no longer auto-load when you start up your application.

D. Uninstalling An Add-in

If you want to get rid of your add-in permanently, you can use the following steps:

  1. Close out of your application (ie Excel)
  2. Delete your add-in file* or move it to a new file path location
  3. Re-open your application (ie Excel)
  4. Navigate to the Add-ins dialog box (see Section A above)
  5. Try to check or uncheck the add-in name and you should get a message box stating that the add-in could not be found and asking if you would like to remove it from the add-in list
  6. Confirm the removal

*Bonus Tip: If you do not know where you saved your add-in, you can carry out the following steps to find the file location on your computer:

  1. Use the shortcut Alt + F11 to open up the Visual Basic Editor
  2. In the Visual Basic Editor window, use the shortcut ctrl + g to open up the Immediate Window
  3. In the Project Pane, highlight the name of your add-in
  4. In the Immediate Window, paste in the following line of code and hit the Enter key

?ThisWorkbook.Path

After executing the above line of code in the Immediate Window, your add-in's file path should be displayed! Here's a visual for you in case those steps were a little confusing.

How to find a forgotten file path of an Excel add-in

5 Ways to Create A Dynamic Auto-Adjusting VBA Range

$
0
0
5 Ways To Create Dynamic VBA Macro Ranges

Dynamic Code Is Vital!

A huge turning point for me when I was teaching myself how to write VBA was being able to create dynamic code. This meant I didn't have to go into my macros and change range addresses in my code every time the size of my data changed (which was typically every day). Through lots of trial and error, I've come up with a list of 5 different methods you can use to turn your static range references into powerful, auto-adjusting machines! All of these code snippets have advantages and disadvantages, so make sure you pick the one that works for your particular situation.

Method 1: UsedRange

The UsedRange method creates a range that includes every cell that contains data in it on the spreadsheet. It is vital that you refresh (recalculate) the UsedRange before using it as the method will pick up ghost cells (cells that had values in them and you used the Delete key to remove the values). Manually you can do this by saving your spreadsheet or you can use the command shown in the below code to refresh with VBA.

Sub DynamicRange()
'Best used when only your target data is on the worksheet

'Refresh UsedRange (get rid of "Ghost" cells)
  Worksheets("Sheet1").UsedRange

'Select UsedRange
  Worksheets("Sheet1").UsedRange.Select

End Sub

Method 2: Ctrl + Alt + Right Arrow/Down Arrow

This code simulates the range that would show up if you were to use the keyboard shortcut Ctrl + Alt + Right Arrow and then Ctrl + Alt + Down Arrow. If the last cell in the first row or the last cell in the first column are empty, this code will not calculate properly.

Sub DynamicRange()
'Best used when first column has value on last row and first row has a value in the last column

Dim sht As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range

Set sht = Worksheets("Sheet1")
Set StartCell = Range("D9")

'Find Last Row and Column
  LastRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row
  LastColumn = sht.Cells(StartCell.Row, sht.Columns.Count).End(xlToLeft).Column

'Select Range
  sht.Range(StartCell, sht.Cells(LastRow, LastColumn)).Select

End Sub

Method 3: SpecialCells - LastCell

This code uses the SpecialCells method (the non-VBA terminology is called Go To Cells) to search for the last cell containing data on the spreadsheet. Once this cell is found, the code can use the cell reference of the "last cell" to determine the last row and column.

Sub DynamicRange()
'Best used when you want to include all data stored on the spreadsheet

Dim sht As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range

Set sht = Worksheets("Sheet1")
Set StartCell = Range("D9")

'Refresh UsedRange
  Worksheets("Sheet1").UsedRange

'Find Last Row and Column
  LastRow = StartCell.SpecialCells(xlCellTypeLastCell).Row
  LastColumn = StartCell.SpecialCells(xlCellTypeLastCell).Column

'Select Range
  sht.Range(StartCell, sht.Cells(LastRow, LastColumn)).Select
  
End Sub

Method 4: CurrentRegion

This example uses the CurrentRegion method. CurrentRegion tries to calculate the range associated with a cell reference by analyzing the surrounding cells. If there is a completely blank row or blank column, CurrentRegion stops looking and assumes that you were only wanting the data that was connected with your starting point. Make sure there are no chances of your data having a completely blank row or column before using this method.

Sub DynamicRange()
'Best used when your data does not have any entirely blank rows or columns

Dim sht As Worksheet
Dim StartCell As Range

Set sht = Worksheets("Sheet1")
Set StartCell = Range("D9")

'Select Range
  StartCell.CurrentRegion.Select

End Sub

Method 5: Static Columns

I've experienced lots of situations where the column length never changed and the VBA code just needed to dynamically adjust for row length. In cases like this, you may not want to write lines to look for the last column. The below code shows you how to adjust a ranges row length dynamically.

Note: You could also use the LastRow calculation used in Method 2 instead of the Find calculation shown below.

Sub DynamicRange()
'Best used when column length is static

Dim sht As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range

Set sht = Worksheets("Sheet1")
Set StartCell = Range("D9")

'Refresh UsedRange
  Worksheets("Sheet1").UsedRange

'Find Last Row
  LastRow = sht.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

'Select Range
  sht.Range("D9:M" & LastRow).Select

End Sub

What Can I Do With A Dynamic Range?

There are a ton of scenarios that may require you to have an automatically expanding and collapsing range reference. Examples could be:

  • Resizing a Pivot Table source range
  • Looping through cells in a data set
  • Deleting only the raw data range

There are many, many more examples of this and I'm am sure you can think of a few examples yourself. Let me know in the comments section below how you use resizing a range in your macro code!  Also, if you can think of any other ways to use VBA code to resize your ranges automatically, post your coding method in the comments section so we can improve the current list.  I look forward to reading about your experiences.

How Do I Modify This To Fit My Specific Needs?

Chances are this post did not give you the exact answer you were looking for. We all have different situations and it's impossible to account for every particular need one might have. That's why I want to share with you: My Guide to Getting the Solution to your Problems FAST! In this article, I explain the best strategies I have come up with over the years to getting quick answers to complex problems in Excel, PowerPoint, VBA, you name it

I highly recommend that you check this guide out before asking me or anyone else in the comments section to solve your specific problem. I can guarantee 9 times out of 10, one of my strategies will get you the answer(s) you are needing faster than it will take me to get back to you with a possible solution. I try my best to help everyone out, but sometimes I don't have time to fit everyone's questions in (there never seem to be quite enough hours in the day!).

I wish you the best of luck and I hope this tutorial gets you heading in the right direction!

Chris "Macro" Newman :)

The VBA Guide To Sending Excel Attachments Through Outlook

$
0
0
VBA Macro Guide Generating Outlook Email Messages With Excel File Attachement

Quickly Emailing Your Spreadsheets

I absolutely love using the Email As Attachment functionality provided by Excel. It's great for quickly sending one-off data requests to someone throughout the day. The only thing I dislike about this built-in feature is the lack of customization as I find myself repeatedly making the same changes over and over again.

This annoyance inspired me to create a couple of VBA macros allowing me to add a little more functionality to Microsoft's Email As Attachment idea.

For one, I hate not being able to name the attached file. I can't tell you how many times I've attached a file named "Book1.xlsx" to someone. I also like to add some sort of message in the email such as "Please see attached" or "Attached is your requested data". Having to type this out every time can be a bit annoying.

So I would like to share with you what I use to email my Excel workbooks and worksheets as attachments. Now, this code was intended to suit my needs, but hopefully I've added enough comments to allow you to easily tweak it to fit your specific needs. 

Sample of what this VBA code will output

Sample of what this VBA code will output

Email ActiveWorkbook As Outlook Attachment

This VBA macro code with add the entire ActiveWorkbook as an attachment to a brand new Outlook message.

Sub EmailWorkbook()
'PURPOSE: Create email message with ActiveWorkbook attached
'SOURCE: www.TheSpreadsheetGuru.com

Dim SourceWB As Workbook
Dim DestinWB As Workbook
Dim OutlookApp As Object
Dim OutlookMessage As Object
Dim TempFileName As Variant
Dim ExternalLinks As Variant
Dim TempFilePath As String
Dim FileExtStr As String
Dim DefaultName As String
Dim UserAnswer As Long
Dim x As Long

Set SourceWB = ActiveWorkbook

'Check for macro code residing in
  If Val(Application.Version) >= 12 Then
    If SourceWB.FileFormat = 51 And SourceWB.HasVBProject = True Then
      UserAnswer = MsgBox("There was VBA code found in this xlsx file. " & _
        "If you proceed the VBA code will not be included in your email attachment. " & _
        "Do you wish to proceed?", vbYesNo, "VBA Code Found!")
    
    If UserAnswer = vbNo Then Exit Sub 'Handle if user cancels
  
    End If
  End If

'Determine Temporary File Path
  TempFilePath = Environ$("temp") & "\"

'Determine Default File Name for InputBox
  If SourceWB.Saved Then
    DefaultName = Left(SourceWB.Name, InStrRev(SourceWB.Name, ".") - 1)
  Else
    DefaultName = SourceWB.Name
  End If

'Ask user for a file name
  TempFileName = Application.InputBox("What would you like to name your attachment? (No Special Characters!)", _
    "File Name", Type:=2, Default:=DefaultName)
    
    If TempFileName = False Then Exit Sub 'Handle if user cancels
  
'Determine File Extension
  If SourceWB.Saved = True Then
    FileExtStr = "." & LCase(Right(SourceWB.Name, Len(SourceWB.Name) - InStrRev(SourceWB.Name, ".", , 1)))
  Else
    FileExtStr = ".xlsx"
  End If

'Optimize Code
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.DisplayAlerts = False

'Save Temporary Workbook
  SourceWB.SaveCopyAs TempFilePath & TempFileName & FileExtStr
  Set DestinWB = Workbooks.Open(TempFilePath & TempFileName & FileExtStr)

'Break External Links
  ExternalLinks = DestinWB.LinkSources(Type:=xlLinkTypeExcelLinks)

    'Loop Through each External Link in ActiveWorkbook and Break it
      On Error Resume Next
        For x = 1 To UBound(ExternalLinks)
          DestinWB.BreakLink Name:=ExternalLinks(x), Type:=xlLinkTypeExcelLinks
        Next x
      On Error GoTo 0
      
'Save Changes
  DestinWB.Save

'Create Instance of Outlook
  On Error Resume Next
    Set OutlookApp = GetObject(class:="Outlook.Application") 'Handles if Outlook is already open
  Err.Clear
    If OutlookApp Is Nothing Then Set OutlookApp = CreateObject(class:="Outlook.Application") 'If not, open Outlook
    
    If Err.Number = 429 Then
      MsgBox "Outlook could not be found, aborting.", 16, "Outlook Not Found"
      GoTo ExitSub
    End If
  On Error GoTo 0

'Create a new email message
  Set OutlookMessage = OutlookApp.CreateItem(0)

'Create Outlook email with attachment
  On Error Resume Next
    With OutlookMessage
     .To = ""
     .CC = ""
     .BCC = ""
     .Subject = TempFileName
     .Body = "Please see attached." & vbNewLine & vbNewLine & "Chris"
     .Attachments.Add DestinWB.FullName
     .Display
    End With
  On Error GoTo 0

'Close & Delete the temporary file
  DestinWB.Close SaveChanges:=False
  Kill TempFilePath & TempFileName & FileExtStr

'Clear Memory
  Set OutlookMessage = Nothing
  Set OutlookApp = Nothing
  
'Optimize Code
ExitSub:
  Application.ScreenUpdating = True
  Application.EnableEvents = True
  Application.DisplayAlerts = True

End Sub

Email Selected Worksheets As Outlook Attachment

This VBA macro will attach only the selected tabs within the ActiveWorkbook to a new Outlook email message.

Sub EmailSelectedSheets()
'PURPOSE: Create email message with only Selected Worksheets attached
'SOURCE: www.TheSpreadsheetGuru.com

Dim SourceWB As Workbook
Dim DestinWB As Workbook
Dim OutlookApp As Object
Dim OutlookMessage As Object
Dim TempFileName As Variant
Dim ExternalLinks As Variant
Dim TempFilePath As String
Dim FileExtStr As String
Dim DefaultName As String
Dim UserAnswer As Long
Dim x As Long

'Optimize Code
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.DisplayAlerts = False

'Copy only selected sheets into new workbook
  Set SourceWB = ActiveWorkbook
  SourceWB.Windows(1).SelectedSheets.Copy
  Set DestinWB = ActiveWorkbook

'Check for macro code residing in
  If Val(Application.Version) >= 12 Then
    If SourceWB.FileFormat = 51 And SourceWB.HasVBProject = True Then
      UserAnswer = MsgBox("There was VBA code found in this xlsx file. " & _
        "If you proceed the VBA code will not be included in your email attachment. " & _
        "Do you wish to proceed?", vbYesNo, "VBA Code Found!")
    
    'Handle if user cancels
      If UserAnswer = vbNo Then
        DestinWB.Close SaveChanges:=False
        GoTo ExitSub
      End If
      
    End If
  End If

'Determine Temporary File Path
  TempFilePath = Environ$("temp") & "\"

'Determine Default File Name for InputBox
  If SourceWB.Saved Then
    DefaultName = Left(SourceWB.Name, InStrRev(SourceWB.Name, ".") - 1)
  Else
    DefaultName = SourceWB.Name
  End If

'Ask user for a file name
  TempFileName = Application.InputBox("What would you like to name your attachment? (No Special Characters!)", _
    "File Name", Type:=2, Default:=DefaultName)
    
    If TempFileName = False Then GoTo ExitSub 'Handle if user cancels
  
'Determine File Extension
  If SourceWB.Saved = True Then
    FileExtStr = "." & LCase(Right(SourceWB.Name, Len(SourceWB.Name) - InStrRev(SourceWB.Name, ".", , 1)))
  Else
    FileExtStr = ".xlsx"
  End If

'Break External Links
  ExternalLinks = DestinWB.LinkSources(Type:=xlLinkTypeExcelLinks)

    'Loop Through each External Link in ActiveWorkbook and Break it
      On Error Resume Next
        For x = 1 To UBound(ExternalLinks)
          DestinWB.BreakLink Name:=ExternalLinks(x), Type:=xlLinkTypeExcelLinks
        Next x
      On Error GoTo 0
      
'Save Temporary Workbook
  SourceWB.SaveCopyAs TempFilePath & TempFileName & FileExtStr

'Create Instance of Outlook
  On Error Resume Next
    Set OutlookApp = GetObject(class:="Outlook.Application") 'Handles if Outlook is already open
  Err.Clear
    If OutlookApp Is Nothing Then Set OutlookApp = CreateObject(class:="Outlook.Application") 'If not, open Outlook
    
    If Err.Number = 429 Then
      MsgBox "Outlook could not be found, aborting.", 16, "Outlook Not Found"
      GoTo ExitSub
    End If
  On Error GoTo 0

'Create a new email message
  Set OutlookMessage = OutlookApp.CreateItem(0)

'Create Outlook email with attachment
  On Error Resume Next
    With OutlookMessage
     .To = ""
     .CC = ""
     .BCC = ""
     .Subject = TempFileName
     .Body = "Please see attached." & vbNewLine & vbNewLine & "Chris"
     .Attachments.Add TempFilePath & TempFileName & FileExtStr
     .Display
    End With
  On Error GoTo 0

'Close & Delete the temporary file
  DestinWB.Close SaveChanges:=False
  Kill TempFilePath & TempFileName & FileExtStr

'Clear Memory
  Set OutlookMessage = Nothing
  Set OutlookApp = Nothing
  
'Optimize Code
ExitSub:
  Application.ScreenUpdating = True
  Application.EnableEvents = True
  Application.DisplayAlerts = True

End Sub

Take Your Emailing To The Next Level

If you found this VBA code useful, you are sure to love my highly acclaimed Exporter Template. This Excel tool will allow you to automate how you save your files and who you send them too.

Click the below banner to learn more about this amazingly powerful tool!

The Exporter Excel Template

How Do I Modify This To Fit My Specific Needs?

Chances are this post did not give you the exact answer you were looking for. We all have different situations and it's impossible to account for every particular need one might have. That's why I want to share with you: My Guide to Getting the Solution to your Problems FAST! In this article, I explain the best strategies I have come up with over the years to getting quick answers to complex problems in Excel, PowerPoint, VBA, you name it

I highly recommend that you check this guide out before asking me or anyone else in the comments section to solve your specific problem. I can guarantee 9 times out of 10, one of my strategies will get you the answer(s) you are needing faster than it will take me to get back to you with a possible solution. I try my best to help everyone out, but sometimes I don't have time to fit everyone's questions in (there never seem to be quite enough hours in the day!).

I wish you the best of luck and I hope this tutorial gets you heading in the right direction!

Chris "Macro" Newman :)

Online Excel & VBA Resources

$
0
0
Excel & VBA Blog Forum Resource Directory Guide

Your Excel Resource Guide

I'm sure every Excel blog out there has some sort of directory page with recommendations of other great resources and it's about time this blog puts one together. Feel free to help shape the links on this page and I hope you discover at least one new website that can teach you a thing or two about Excel!

[Active] blogs are currently posting tutorial articles at least 4 times per month


Excel Blogs

 

VBA/Development Blogs

International (Non-English) Blogs

*I don't know any foreign languages, so if you know of any great non-english Excel blogs, let me know below in the comments section and I'll start a list

Forums


How To Easily Follow Your Favorites

Most blogs (including this one) don't post on a pre-scheduled basis. A few years ago, I would waste so much time manually checking a mental list of blogs to see if any of them had posted new tutorials. A year later, I started reading up on what RSS feed readers were and they changed my life forever! 

RSS feeds push new content that was posted on blogs from only the websites you designate. A feed reader compiles the information the RSS feeds pump out. It's like having your own personal online newspaper, filled daily with only content from websites you care about.

I personally use Feedly as my RSS feed reader and highly recommend their website. It's a completely free tool that will change the way you consume your content....so at least give it a try!

What New Site Have You Discovered?

I'm sure there is at least one site you haven't heard of or visited yet. Give them a shot and see if you can learn something new today. Leave a comment below if you were pleasantly surprised or impressed by any of the links you clicked on...or if you just want to give your favorite blog a public shout-out. I look forward to reading your responses!

Help Me Update And Maintain

There are thousands of Excel related blogs out there and there's no way I can follow or search out all of them, so that's where I need your help. If there's a blog or forum out there that pushes or has pushed out a ton of awesome Excel-related content, please leave a comment below with the website name so I can update this page's list.

Also, it would be amazing if you can help me annotate which websites are currently active and which blogs are not currently generating new content. Thank you for your help!

Easy Step-By-Step Instructions To Create Your First Excel Ribbon Add-in

$
0
0
Step by steph how to easily develope an Excel addin for your company

One of the most prosperous skills I have picked up over the years as a financial analyst has been the ability to create custom Excel add-ins specific to my department and company's needs. This one skill I have been able to provide to my company has saved numerous people time, frustration, and money. While it took me well over a year to teach myself how to create top-notch add-ins, I want to let you in on a little secret....it's really NOT THAT HARD! And today I want to share with you just how easy it can be to build an Excel add-in that looks amazing and will provide tremendous value to your company as well as to your professional career.

If this article helped you and wouldn't mind helping me out in return, I have a brief 2 question survey that I would love for you to take here or at the bottom of this article. Your answers will help me better understand what else I should write about concerning creating Excel add-ins. Plus the entire survey is done with Excel Online....how cool is that?!

Sure, I'll Take The Survey!

In this article, I will walk you through 5 simple steps:

Step 1: Download my free template (I have done all the difficult, nerdy stuff for you in this file)
Step 2: Link your macros and macro descriptions to the Ribbon buttons
Step 3: Test your buttons and make sure they work 
Step 4: Choose the icons you want to display (Microsoft provides thousands for free!)
Step 5: Save your template as an add-in file and install/share

And Look What You Can Create!

Create An Excel Add-in From My RibbonX Template

Step 1: Download The Template

I went ahead and did all the tricky stuff for you and set up a template to give you a great head start. You can download this template by clicking the button below and signing up for my tips email newsletter. Once signed up, you will instantly gain access to the private webpage where you can download the template. This will allow you to skip all the difficult Ribbon coding.

       Already Subscribed? Click HERE to log-in to the "Example Files" section

     Already Subscribed? Click HERE to log-in to the "Example Files" section

 

After you've filled out the sign-up form, go check your email inbox and you should have two emails, one asking for confirmation to the Guru Newsletter and the other with a link to download the template you will need to complete the rest of this tutorial. Open this file and move on to Step 2!

Step 2: Link Your Macros

Once you've received and opened your brand spanking new Excel Ribbon template, let's dig into the VBA and link all your macro code snippets so they can be triggered by your Ribbon buttons. I am going to run through an example where I want to create a ribbon with just one macro button. Before we begin, make sure you have the file open and are looking at the Visual Basic Editor (shortcut key Alt + F11).

1. Hide Unused Groups & Buttons

Since I only want to create an add-in with one button and the template holds 50buttons, I am going to want to hide the other 49 buttons. To do this, I need to navigate to the RibbonSetup module and then down to the GetVisible subroutine. You should see a Case statement that goes through each button name (ie myButton#) and tells the Ribbon whether to show the button (True) or hide it (False). Since I only want one button showing in the example, I'm going to make only the first button (myButton1) have a value of True. 

Now since the buttons are sectioned off into groups, I can just make the entire group not visible by modifying the Case Statements dealing with group IDs. In the example below I show GroupB not being visible.

Click to enlarge

Click to enlarge

2. Add Your Macro Code

Next, let's add our macro code. I'm just going to use a simple piece of code that does the PasteSpecial command "Pastes Values Only" with the data currently copied to the clipboard.

  1. Navigate to the Macros module and paste in your macro code.
  2. Go back to the RibbonSetup module and scroll to the RunMacro subroutine
  3. Add the macro name to the corresponding button name (overwriting the DummyMacro name)
Click to enlarge

Click to enlarge

3. Add A Screentip For Your Macros

A great way to help your users or yourself remember what a button does is to include a Screentip. A Screentip is a brief description that reminds the user what a button does while hovering over it. You see Screentips all the time in the normal Ribbon tabs, but you may have never noticed them. Go ahead and hover over a button oh your Home tab and you'll see some examples.

Click to enlarge

Click to enlarge

4. Add Your Tab, Group, & Button Names To The Ribbon UI

To finish off this section we are going to go down to the GetLabel subroutine within the RibbonSetup module. Similar to adding a Screentip, you can add a custom label via this macro that will display beneath your button on the Ribbon.

For this example, let's call our Tab "Company", our group "PasteSpecial", and the button "Paste Values". As shown below, all we need to do is navigate to the GetLabel subroutine and modify the Labeling variable value to equal the text value we want displayed on the Ribbon tab.

Click to enlarge

Click to enlarge

At this point, we have linked our macro to a button, we've labeled the button, and provided a screentip so our users know what the button does. The major setup pieces are complete. Let's move on to step 3!

Step 3: Test Your Buttons

This is a brief step but a very important one. After you have linked all your macros to the buttons on your Ribbon, you will want to save your file and close out of it. Re-open the file and see if all your setting tweaks actually flowed into the Macros tab (or in this example the Company tab). Also, start testing your macros to make sure they are all linked to the proper buttons and running as expected.

Step 4: Choose Your Icons

Next, is one of my favorite steps when designing a new add-in, picking out the icons! You might be wondering, how much money am I going to have to spend to get some nice looking icons for my add-in? Well lucky for us, Microsoft has been gracious enough to give everyone complete access to all of their fancy icons used throughout the Office Suite.

So how do we get these awesome icons? Well, remember all that work I did for you to create your handy starting point template? You don't have to worry about finding the icons at all. All you need to do is tell Microsoft which icons to use by typing out their name in your VBA code. Just navigate to the GetImage subroutine and enter in the icon name with the respective button line. Since our example macro deals with pasting, I am going to use the PasteValues icon.

Click to enlarge

Click to enlarge

How Do You Get The Icon Names?

There are a few resources out there that have the Ribbon icon names, but I personally prefer the Excel file Microsoft created called Office 2007 Icons Gallery. This file displays all the icon images in 9 galleries up in the Developer tab of the Ribbon. If you hover over an image, the image's name will appear in the ScreenTip box. You will need to copy this name verbatim (it is case sensitive!) and add it into the VBA macro called GetImage(), in the respective "case" section. Below is how I found the Page Break icon name.

Let me say it again: the icon name IS CASE SENSITIVE! So make sure you capitalize the correct characters.

Click to enlarge

Click to enlarge

How Do You Change The Icon Size?

As you may have noticed when you first opened up the template file, not all the icons are the same size. There are two available sizes that Microsoft allows you to make your icons (large or small). The size of what your icons will be is completely up to you. You may want to make important or heavily used icons large, while making other icons small to save space.

To change the size of an icon, naviage to the GetSize() subroutine and simply change your respective buttons to either equal Large or Small.

You will need to save your file and re-open it to implement the changes.

Click to enlarge

Click to enlarge

Step 5: Save File As An Add-in

The last step is to save the file as an add-in file. Excel add-in files have a file extension of ".xlam", so make sure you select that extension type when you are saving. After you have saved your add-in file, you can close your Excel template (the .xlsm file) and install your lovely new add-in! If you don't know how to install an add-in, you can check out my How to Install a VBA Add-in post that will teach you how to do this.

Congratulations, You Have Developed Your First Add-in!

You've Created Your First VBA RibbonX Excel Addin

You're all done! In just 5 simple steps, you were able to create an awesome and very professional-looking Ribbon-based add-in that you can use for yourself, your team, or even your entire company. Hopefully, I was able to show you that creating add-ins isn't rocket science but most people don't know that. Use this to your advantage and use your new learned skill to impress your boss or even your boss' boss! If you don't mind sharing, I'd love to see how your add-in turned out. Feel free to post a screenshot of what you were able to create in the comments section below!


Can You Help Me Improve?

I'm trying to gather some information about how I can develop great content covering the creation of your own Excel add-ins. Would you be able to take a couple minutes to fill out my 2 question survey? It would be a tremendous help in giving me some direction. Thank you!

Take Survey

The VBA Guide To Interacting With Text (.Txt) Files

$
0
0
VBA Create Delete Modify Text Files

Why Text Files?

Text files can be a very fast and simple way to read and store information. I like to use them to save settings for my VBA add-ins and I have seen situations where databases have exported large amounts of data into .txt files instead of Excel files (especially back in the days with Excel 2003). Below are the main techniques I use to create, modify, extract data, and delete text files.

Some Terminology

When we are working with text files, there will be some terminology that you probably haven't seen or used before when writing VBA code.  Let's walk through some of the pieces you will see throughout the code in this guide.

For Output - When you are opening the text file with this command, you are wanting to create or modify the text file. You will not be able to pull anything from the text file while opening with this mode.

For Input - When you are opening the text file with this command, you are wanting to extract information from the text file. You will not be able to modify the text file while opening it with this mode.

FreeFile - Is used to supply a file number that is not already in use. This is similar to referencing Workbook(1) vs. Workbook(2). By using FreeFile, the function will automatically return the next available reference number for your text file. 

Write - This writes a line of text to the file surrounding it with quotations

Print - This writes a line of text to the file without quotations


VBA For Creating A Text File

Sub TextFile_Create()
'PURPOSE: Create A New Text File
'SOURCE: www.TheSpreadsheetGuru.com

Dim TextFile As Integer
Dim FilePath As String

'What is the file path and name for the new text file?
  FilePath = "C:\Users\chris\Desktop\MyFile.txt"

'Determine the next file number available for use by the FileOpen function
  TextFile = FreeFile

'Open the text file
  Open FilePath For Output As TextFile

'Write some lines of text
  Print #TextFile, "Hello Everyone!"
  Print #TextFile, "I created this file with VBA."
  Print #TextFile, "Goodbye"
  
'Save & Close Text File
  Close TextFile

End Sub

VBA For Extracting All The Text From A Text File

Sub TextFile_PullData()
'PURPOSE: Send All Data From Text File To A String Variable
'SOURCE: www.TheSpreadsheetGuru.com

Dim TextFile As Integer
Dim FilePath As String
Dim FileContent As String

'File Path of Text File
  FilePath = "C:\Users\chris\Desktop\MyFile.txt"

'Determine the next file number available for use by the FileOpen function
  TextFile = FreeFile

'Open the text file
  Open FilePath For Input As TextFile

'Store file content inside a variable
  FileContent = Input(LOF(TextFile), TextFile)

'Report Out Text File Contents
  MsgBox FileContent

'Clost Text File
  Close TextFile

End Sub

VBA For Modifying A Text File (With Find/Replace)

Sub TextFile_FindReplace()
'PURPOSE: Modify Contents of a text file using Find/Replace
'SOURCE: www.TheSpreadsheetGuru.com

Dim TextFile As Integer
Dim FilePath As String
Dim FileContent As String

'File Path of Text File
  FilePath = "C:\Users\chris\Desktop\MyFile.txt"

'Determine the next file number available for use by the FileOpen function
  TextFile = FreeFile

'Open the text file in a Read State
  Open FilePath For Input As TextFile

'Store file content inside a variable
  FileContent = Input(LOF(TextFile), TextFile)

'Clost Text File
  Close TextFile
  
'Find/Replace
  FileContent = Replace(FileContent, "Goodbye", "Cheers")

'Determine the next file number available for use by the FileOpen function
  TextFile = FreeFile

'Open the text file in a Write State
  Open FilePath For Output As TextFile
  
'Write New Text data to file
  Print #TextFile, FileContent

'Clost Text File
  Close TextFile

End Sub

VBA For Deleting A Text File

Sub TextFile_Delete()
'PURPOSE: Delete a Text File from your computer
'SOURCE: www.TheSpreadsheetGuru.com

Dim FilePath As String

'File Path of Text File
  FilePath = "C:\Users\chris\Desktop\MyFile.txt"

'Delete File
  Kill FilePath

End Sub

VBA For Fill Array With Delimited Data From Text File

Sub DelimitedTextFileToArray()
'PURPOSE: Load an Array variable with data from a delimited text file
'SOURCE: www.TheSpreadsheetGuru.com

Dim Delimiter As String
Dim TextFile As Integer
Dim FilePath As String
Dim FileContent As String
Dim LineArray() As String
Dim DataArray() As String
Dim TempArray() As String
Dim rw As Long, col As Long

'Inputs
  Delimiter = ";"
  FilePath = "C:\Users\chris\Desktop\MyFile.txt"
  rw = 0
  
'Open the text file in a Read State
  TextFile = FreeFile
  Open FilePath For Input As TextFile
  
'Store file content inside a variable
  FileContent = Input(LOF(TextFile), TextFile)

'Close Text File
  Close TextFile
  
'Separate Out lines of data
  LineArray() = Split(FileContent, vbCrLf)

'Read Data into an Array Variable
  For x = LBound(LineArray) To UBound(LineArray)
    If Len(Trim(LineArray(x))) <> 0 Then
      'Split up line of text by delimiter
        TempArray = Split(LineArray(x), Delimiter)
      
      'Determine how many columns are needed
        col = UBound(TempArray)
      
      'Re-Adjust Array boundaries
        ReDim Preserve DataArray(col, rw)
      
      'Load line of data into Array variable
        For y = LBound(TempArray) To UBound(TempArray)
          DataArray(y, rw) = TempArray(y)
        Next y
    End If
    
    'Next line
      rw = rw + 1
    
  Next x

End Sub

How Do I Modify This To Fit My Specific Needs?

Chances are this post did not give you the exact answer you were looking for. We all have different situations and it's impossible to account for every particular need one might have. That's why I want to share with you: My Guide to Getting the Solution to your Problems FAST! In this article, I explain the best strategies I have come up with over the years to getting quick answers to complex problems in Excel, PowerPoint, VBA, you name it

I highly recommend that you check this guide out before asking me or anyone else in the comments section to solve your specific problem. I can guarantee 9 times out of 10, one of my strategies will get you the answer(s) you are needing faster than it will take me to get back to you with a possible solution. I try my best to help everyone out, but sometimes I don't have time to fit everyone's questions in (there never seem to be quite enough hours in the day!).

I wish you the best of luck and I hope this tutorial gets you heading in the right direction!

Chris "Macro" Newman :)

Using Cell Formatting Logic With Excel Formulas

$
0
0
Excel Functions IsBold IsColor IsItalic IsUnderlined

Wishful Thinking?

 Have you ever had a time where you wished you could write an IF formula in Excel based on whether or not a cell was filled with the color green or not? Unfortunately, Excel doesn't have a built-in "IsGreen" function you can call to perform such logic. However, with the power of VBA you can write your own functions and actually call them from the Formula Bar!  This can be extremely powerful and extends Excel's logical prowess to a near limitless level! Let's take a look at how we can add our own functions into our spreadsheets.

Where Do I Write The Function Logic?

I recommend storing your custom functions inside a VBA module. Here are the steps to create a brand new module within your spreadsheet.

  1. Inside your spreadsheet use the keyboard shortcut Alt + F11 to open up the Visual Basic Editor window
  2. On the left-hand side of the window, you should see a Project pane that will display every Excel workbook/add-in you currently have open
  3. Find the Project Name that matches the Excel file you want to store the functions in and right-click on the Project Name
  4. Inside the menu that pops up, go to Insert -> Module
  5. A blank white canvas should appear on your screen and this is where you will want to write or paste in your custom function code

Examples of Functions You Can Add

This is where you can let your imagination run wild (especially if you have a good grasp on how to write VBA). But in case you are new to VBA (you can learn how to get started learning to write VBA here),  I am going to provide you with a few common functions that might be useful when trying to logically analyze a cell's formatting.

Function To Determine If Cell Text Is Bold

Function ISBOLD(cell As Range) As Boolean
'PURPOSE: Determine if cell has bold text or not
'SOURCE: www.TheSpreadsheetGuru.com

'Ensure function will recalculate after spreadsheet changes
  Application.Volatile True

'Test Cell Value
  On Error GoTo PartiallyBold
    ISBOLD = cell.Font.Bold
  On Error GoTo 0

Exit Function

'Handle if only part of the cell value is bolded
PartiallyBold:
  If Err.Number = 94 Then ISBOLD = True

End Function

Function To Determine If Cell Text Is Italicized

Function ISITALIC(cell As Range) As Boolean
'PURPOSE: Determine if cell has italicized text or not
'SOURCE: www.TheSpreadsheetGuru.com

'Ensure function will recalculate after spreadsheet changes
  Application.Volatile True

'Test Cell Value
  On Error GoTo PartiallyItalic
    ISITALIC = cell.Font.Italic
  On Error GoTo 0

Exit Function

'Handle if only part of the cell value is italicized
PartiallyItalic:
  If Err.Number = 94 Then ISITALIC = True

End Function

Function To Determine If Cell Text Is Underlined

Function ISUNDERLINED(cell As Range) As Boolean
'PURPOSE: Determine if cell has underlined text or not
'SOURCE: www.TheSpreadsheetGuru.com

'Ensure function will recalculate after spreadsheet changes
  Application.Volatile True

'Test Cell Value
  If cell.Font.Underline = xlNone Then
    ISUNDERLINED = False
  Else
    ISUNDERLINED = True
  End If

End Function

Function To Determine If Cell Text Is A Specific Color

Function ISFONTCOLOR(cell As Range, TargetColor As Range) As Boolean
'PURPOSE: Test if cell font color matches a specified cell fill color
'NOTE: Color changes will not trigger your spreadsheet to re-calculate
'SOURCE: www.TheSpreadsheetGuru.com

'Ensure function will recalculate after spreadsheet changes
  Application.Volatile True

'Test Cell Font Color
  If cell.Font.Color = TargetColor.Interior.Color Then
    ISFONTCOLOR = True
  Else
    ISFONTCOLOR = False
  End If

End Function

Function To Determine If Cell Fill Is A Specific Color

Function ISFILLCOLOR(cell As Range, TargetColor As Range) As Boolean
'PURPOSE: Test if cell fill color matches a specified cell fill color
'NOTE: Color changes will not trigger your spreadsheet to re-calculate
'SOURCE: www.TheSpreadsheetGuru.com

'Ensure function will recalculate after spreadsheet changes
  Application.Volatile True

'Test Cell Fill Color
  If cell.Interior.Color = TargetColor.Interior.Color Then
    ISFILLCOLOR = True
  Else
    ISFILLCOLOR = False
  End If

End Function

Calling A Custom Function

Once you have written your function in the VBA module, you can then start to use it! Simply begin typing the function inside the formula bar and you will see your custom function appear as a viable selection. Note that you will not get any ScreenTips with your custom functions (come on Microsoft!), so you will need to memorize how to properly use your custom function.

Use A Custom Function IsBold In Formula Bar

Formula Recalculation

You will need to be careful with these formulas since changing the format of a cell does not trigger a spreadsheet recalculation. Always make sure you hit the F9 key before you begin your analysis while using a custom function that takes into account formatting in your spreadsheets.

Download An Example File With These Functions

To help you further, I have created an example workbook with all the custom functions described in this article put to use so you can see them in action. As always, in order to download this example file you will need to be a subscriber of my free tips newsletter.  If you click the green button below you can quickly sign up and be emailed the password to gain access to the subscribers-only area of this website.

                                                       Already Subscribed? Click HERE to navigate to the "Example Files" section

                                                       Already Subscribed? Click HERE to navigate to the "Example Files" section

How Do I Modify This To Fit My Specific Needs?

Chances are this post did not give you the exact answer you were looking for. We all have different situations and it's impossible to account for every particular need one might have. That's why I want to share with you: My Guide to Getting the Solution to your Problems FAST! In this article, I explain the best strategies I have come up with over the years to getting quick answers to complex problems in Excel, PowerPoint, VBA, you name it

I highly recommend that you check this guide out before asking me or anyone else in the comments section to solve your specific problem. I can guarantee 9 times out of 10, one of my strategies will get you the answer(s) you are needing faster than it will take me to get back to you with a possible solution. I try my best to help everyone out, but sometimes I don't have time to fit everyone's questions in (there never seem to be quite enough hours in the day!).

I wish you the best of luck and I hope this tutorial gets you heading in the right direction!

Chris "Macro" Newman :)

How To Trigger Your VBA Macros To Run Based On A Specific Cell Value Change

$
0
0
How To Trigger Your VBA Macros To Run Based On A Specific Cell Value Change

Today we are going to discuss how you can automatically make your VBA code execute based on a specific cell value being changed. Behind the scenes, Excel keeps track of specific events that occur while the user is working on their spreadsheet. These tracked events are called Event Handlers and we can use Event Handlers as triggers to kick off our macros based on what our users are doing to their spreadsheets.

What Are Some Examples of Event Handlers?

There are a bunch of Event Handlers available to you and they fall into two categories: Workbook and Worksheet Events. What the handlers capture is fairly evident by their names, so I won't go into detail on what each on does. But I will go ahead and list some of them out so you can have an idea of what is available to you.


Workbook Events

  • Open
  • SheetChange
  • SheetActivate
  • BeforeClose
  • BeforeSave
  • NewChart

Worksheet Events

  • Change
  • Activate
  • BeforeDelete
  • BeforeDoubleClick
  • BeforeRightClick
  • SelectionChange

Where Are Event Handlers Located?

Event Handlers are not stored in your typical module location. They are actually stored inside either your Workbook or Worksheet object. To get to the "coding area" of either your workbook or worksheet, you simply double-click ThisWorkbook or the sheet name (respectively) within your desired VBA Project hierarchy tree (within the Project Window of your Visual Basic Editor).

How Do I Add An Event Handler?

Event Handlers have very specific subroutine names and variables. It is very important not to have any typos within the sub name or the variables it declares. To guarantee avoidance of any typos, I always recommend having the Visual Basic Editor set up the Event Handler code for you. To do this,  select either Worksheet or Workbook from the Object drop-down box and then select the Event Handler you wish to use from the Procedure drop-down box.

VBA Event Handler Trigger Macro Code

Let's Walk Through An Example!

Hopefully, you now have some sort of conceptual understanding of Event Handlers, but how do you use them in the real world? Let's walk through a very simple example that will allow us to run some VBA code whenever the Cell G7 contains the word "yes" on our spreadsheet.

Below is going to be our interface where Excel will reveal a joke if you type the word "Yes" into the blank box (Cell G7).

Excel VBA Event Handler Trigger Macro Code

The Example in Action

You can see through the following diagram, immediately after I type in "Yes, tell me a joke!", a super-funny joke magically appears! 

Excel VBA Change Event Handler Trigger Macro Code

The VBA Behind The Spreadsheet

To get this spreadsheet working as intended, I needed to add an Event handler, to capture anytime there was a change to the cell G7. I choose to use the Change Event Handler to make this happen.

What the Change event captures is any change made to your spreadsheet (excluding formatting changes). You'll notice that the Worksheet_Change subroutine has a variable named Target that gets fed into it. This variable is a Range-type and will be the cell that was last changed by the user. So if I changed the value in Cell A1, the Worksheet_Change subroutine would kick off and pass Cell A1 into the Target variable.

With this in mind, we are going to want to test the cell that was changed to see if it matches the cell we are concerned with. We can do this by starting our code off with a very simple If Statement that acts as a door to the rest of the code.

'Determine if change was made to cell G7
  If Target = Range("G7") Then

If the Target cell does not have access to get past the door, then the code ends and it will happen so fast, that your user won't know anything has happened.

Below is the code in full that will test if the word "Yes" was entered into cell G7 anytime a change happens within Sheet1:

'Remove Case Sensitivity
  Option Compare Text

Private Sub Worksheet_Change(ByVal Target As Range)

'Determine if change was made to cell G7
  If Target = Range("G7") Then
    'Determine if the work "yes" is contained within cell g7
      If InStr(1, Range("G7"), "Yes") > 0 Then
        Range("G9").Font.Color = Range("F5").Font.Color
      Else
        Range("G9").Font.Color = Range("G9").Interior.Color
      End If
  End If

End Sub

And here is a diagram of where you would place the code within your VBA Project:

Worksheet Event Handler.png

Why Aren't My Events Getting Captured?

Many people will turn off the tracking of Event to speed up their VBA code. If you are relying on capturing events within your spreadsheet and they don't seem to be working, you can run the following command in the Immediate Window (use the shortcut Ctrl + g to make this window visible) within the Visual Basic Editor.

Just hit your enter key after typing the below phrase into the Immediate Window:

  Application.EnableEvents = True

Get The Example File Used In This Article

Sometimes seeing things in action may help you learn much better than reading about it in an article. That is why I am making the example I walked through in this article available to you. The workbook and its code are completely unlocked so you can dig in and discover how all the magic works.

As always, in order to download this example file you will need to be a subscriber of my free newsletter.  If you click the green button below you can easily sign up and you will be emailed the password to get into the subscribers-only area of this website.

       Already Subscribed? Click HERE to log-in to the "Example Files" section

     Already Subscribed? Click HERE to log-in to the "Example Files" section

 

How Do I Modify This To Fit My Specific Needs?

Chances are this post did not give you the exact answer you were looking for. We all have different situations and it's impossible to account for every particular need one might have. That's why I want to share with you: My Guide to Getting the Solution to your Problems FAST! In this article, I explain the best strategies I have come up with over the years to getting quick answers to complex problems in Excel, PowerPoint, VBA, you name it

I highly recommend that you check this guide out before asking me or anyone else in the comments section to solve your specific problem. I can guarantee 9 times out of 10, one of my strategies will get you the answer(s) you are needing faster than it will take me to get back to you with a possible solution. I try my best to help everyone out, but sometimes I don't have time to fit everyone's questions in (there never seem to be quite enough hours in the day!).

I wish you the best of luck and I hope this tutorial gets you heading in the right direction!

Chris "Macro" Newman :)

Create A Bar Chart With Separate Positive And Negative Colors

$
0
0
Create A Bar Chart With Separate Positive And Negative Colors

Our goal as analysts is to tell a story with our data and it is a well-known fact that data can be consumed much faster through visualization than through text. That is why it is vital that we put serious thought into how we present our data to the leaders we support.

Using different colors in our charts to call out facts about our data is a very good way to instantly tell a story. Your audiences' eyes can instantaneously split the data can focus on the results you want to direct them to first. All this can be done without saying a single word!

Creating Multi-Colored "Single-Series" Bar Charts

Take a look at the two bar charts below. Right away you can tell some of the bars are not like the others and this is good, because you audience is going to be immediately drawn to the unique-looking bars (ie the gray and checkered bars in the example).

Vary the colors of same-series data markers in a chart

Unfortunately, it's not so straightforward to build a chart that looks like the examples shown above. Yes, you could manually change the colors of individual bars each time, but when you do things manually there is a loss of time and a greater chance for errors. So how can we automate this task, allowing our bars to change their format based on the current month's data?

The Short Answer: By using two chart series and making them look like one!

Setting Up Your Chart Data

Vary the colors of same-series data markers in a chart

Instead of using a single line of data for your bar chart, you are going to need to set up 4 rows. The first two rows will house your data and the last two will store your Data Label values. To make your "new" chart data table, you are going to want to use similar formulas to those shown below.

Color Coded Bar Charts with Microsoft Excel

The key to your formulas, is you are going to only want a single value per row within the two sections. For the first two data rows, you are going to want one value in each column to house the actual data point, while the other will have the value of the #NA error. That way in our chart only displays one bar between the two chart series.

You'll need to use the same idea for the data labels, with one row having the data point value and the other having a "" (blank) value.

Creating Your Bar Chart

Now that your data is set up, we can begin creating your chart. Simply highlight the cell range containing your two rows of data, go to the INSERT tab and select a 2-D Column chart (not stacked).

Below are the steps visually (click to enlarge):

Color Coded Bar Charts with Microsoft Excel

Making Two Chart Series Appear As One

In order to create the effect of having only one chart series in your graph, you will simply need to overlap your two series by 100%. This can be done by right-clicking on one of chart bars and selecting the option to Format Data Series. Then select the Series Options icon and find where you can modify the Series Overlap setting (shown below).

Excel Chart Series Overlap Bars Columns

Some Quick Chart Clean Up

This part is just my personal preference, but I will provide a few steps on how I like to clean up my charts to make them easier to look at.

How to Make Bars Different Colors in an Excel Chart

Here's what I did:

  1. Give your chart a relevant title and also make it have a larger font size than the rest of the text within the chart
  2. Remove the Y-Axis Labels. We are going to be adding Data Labels later on, so there is no use having both (it's a bit redundant!)
  3. To save space, I like to have my chart legends overlay the chart area (typically near the upper right or left-hand corners)
  4. Move the X-Axis Labels below all the data (Format Axis > Axis Options > Label Position > Low)
  5. Delete the Gridlines and remove the chart border

Setting Up The Data Labels

This is the part I absolutely hate, but I'm able to get through it by telling myself, "Chris, you only have to do this once, you only have to do this once." 

So let's dive into it! First you are going to need to add Data Labels to both Chart Series. You can do this by right-clicking on a bar within each series and selecting Add Data Labels.

Once you have added both sets of data labels, your chart should look similar to the bar chart shown below. You'll notice that we have all these #N/A errors showing up in the labels. This is why we created the two label rows in your Chart Data section, to rid our chart of these errors.

How to Make Bars Different Colors in an Excel Chart

Linking The Data Labels With A Formula

In order to connect our data labels with a cell value, we will need to do the following steps

  1. Select a single Data Label (by double-clicking the desired label)
  2. Click into the Formula Bar
  3. Select the Cell you wish to pull from and hit the Enter key on your keyboard

You will need to repeat this step for all of your data labels until they are all connected to their respective data point.

Excel Different Colored Column Chart Same Series Appearance

The Polished Result!

Guess what? You now have a chart that can tell a much more effective story!

Spreadsheet Chart Bar Callout Specific Bar in Graph

Learn More With This Example Workbook

I have created a sample workbook with 4 different variations of multi-colored bar charts. The workbook is completely unlocked so you can dig in and discover how the magic works. As always, in order to download this example file you will need to be a subscriber of my free newsletter.  If you click the green button below you can easily sign up and you will be emailed the password to get into the subscribers-only area of this website.

Examples of Multiple colored bar charts Excel Workbook File        Already Subscribed? Click HERE to log-in to the "Example Files" section

     Already Subscribed? Click HERE to log-in to the "Example Files" section

 

How Do I Modify This To Fit My Specific Needs?

Chances are this post did not give you the exact answer you were looking for. We all have different situations and it's impossible to account for every particular need one might have. That's why I want to share with you: My Guide to Getting the Solution to your Problems FAST! In this article, I explain the best strategies I have come up with over the years to getting quick answers to complex problems in Excel, PowerPoint, VBA, you name it

I highly recommend that you check this guide out before asking me or anyone else in the comments section to solve your specific problem. I can guarantee 9 times out of 10, one of my strategies will get you the answer(s) you are needing faster than it will take me to get back to you with a possible solution. I try my best to help everyone out, but sometimes I don't have time to fit everyone's questions in (there never seem to be quite enough hours in the day!).

I wish you the best of luck and I hope this tutorial gets you heading in the right direction!

Chris "Macro" Newman :)

Masking (Hiding) A Password As It Is Entered In An Excel Text Box

$
0
0
Masking Excel Passwords with Text box

Today, I came across a spreadsheet that allowed a user to connect to a remote database via VBA. The spreadsheet had a nifty little interface allowing you to enter your username and password for access to the database. The thing that caught my eye was the password had masked characters, so no one passing by your desk could see your password.

Since I had never seen this in a spreadsheet before, I naturally had to dig in and see how this was done. It turned out to be very easy to setup and in the following steps you too will learn how this neat feature can be accomplished.

Adding The Text Box

First you will need to add the text box where you or your users need to enter in their password. For this, you will need to insert an ActiveX Control Text Box (a Form Control version will not work). To do this:

  1. Go to the Developer Tab
  2. Click Insert inside the Controls group
  3. Go down and click the Text Box icon underneath the ActiveX Controls heading
Inserting ActiveX Control Text Box

After you click the Text Box icon, you can simply draw your text box on your spreadsheet. Below, I did this process twice, so my users could enter in their Username and Password into Text Boxes.

Hiding information with asterisk in Excel Spreadsheet

Adding The Mask

Now for the fun stuff! To get your text box to mask what is being entered into it, you will first need to right-click on the text box while in Design Mode (Developer Tab > Design Mode). From the menu that appears, select Properties.

Hiding password login information in Microsoft Spreadsheet

Next, you will get this form box popping up with an enormous list of settings that you can tweak. We are going to focus on a setting called PasswordChar (about two-thirds of the way down the list). in the PasswordChar field you can enter any character in and the text box will only display that character within your text box. Typically, everyone uses an asterisk (*), but you can use a question mark (?), exclamation mark (!), or whatever your hear desires

Click to enlarge

Click to enlarge

The Final Touches

After you are finished tweaking your text box settings, you will need to exit out of Design Mode. Simply click on the Design Mode button in your ribbon so it is no longer highlighted.

Microsoft Excel Developer Tab Design Mode

By adding a couple personalized tweaks, you can have your very own login screen within Excel!

Create Login Interface in Microsoft Excel Spreadsheet

Security Things To Keep In Mind

While this is a very cool feature, it is important to note even though your password is masked visually, it is still stored within the Excel spreadsheet. You need to be aware of this because someone using VBA could easily pull the password from the text box.

Also, if you simply remove your special character from the PasswordChar field, your password will be revealed within the text box.

To put it simply: this in NOT a secure way to store your login information or any confidential information for that matter.

My Recommendation For Masking Information

I recommend only using this feature for personal spreadsheets that are not shared with anyone else. This feature is really meant to prevent passers-by from catching a glimpse of personal information while displayed on your screen. Excel's password masking feature is not meant for preventing other spreadsheet users from discovering your password. 

How Do I Modify This To Fit My Specific Needs?

Chances are this post did not give you the exact answer you were looking for. We all have different situations and it's impossible to account for every particular need one might have. That's why I want to share with you: My Guide to Getting the Solution to your Problems FAST! In this article, I explain the best strategies I have come up with over the years to getting quick answers to complex problems in Excel, PowerPoint, VBA, you name it

I highly recommend that you check this guide out before asking me or anyone else in the comments section to solve your specific problem. I can guarantee 9 times out of 10, one of my strategies will get you the answer(s) you are needing faster than it will take me to get back to you with a possible solution. I try my best to help everyone out, but sometimes I don't have time to fit everyone's questions in (there never seem to be quite enough hours in the day!).

I wish you the best of luck and I hope this tutorial gets you heading in the right direction!

Chris "Macro" Newman :)

 

Wingdings & Webdings Font Icon Character Map (Printable Cheat Sheet)

$
0
0
Webding Wingding Icon Cheat Sheet Mapping Symbols

All The Icons For The Wingdings and Webdings Fonts

Here is a list of all the icons (by character) for:

  • Webdings font
  • Wingdings font
  • Wingdings 2 font
  • Wingdings 3 font

You can click on the below summary to see all your icon options a little more clearly. Enjoy!

Click to enlarge

Click to enlarge

Why are Icon Fonts Important?

I love using Icon Fonts because they can add great visualizations to your data and dashboards. You might be thinking....

"Chris, doesn't Excel already have pre-built conditional formats that do that for you?" 

Well, yes you are exactly right. BUT, while the conditional formats can be great, there are some instances where they really can be limiting and look unprofessional.

Let's look at this simple Balanced Scorecard example (click the graphic to enlarge it).

Balanced Scorecard Example Webdings Icons

In the scorecard examples above, I used the built-in Excel icon conditional formatting and then created a similar scorecard using the Webdings font (character "n") and some conditional formatting to change the color.

The first thing you might notice is when you enlarge this image, the conditionally formatted circles are blurry (this is due to me increasing the font size). This looks extremely unprofessional and might distract/irratate your audience.

The second thing that you might notice is with icon fonts I have the freedom to make the stoplights any color I want! This can make your tables match your company's specific branding color palette, which will make it look amazing in presentations (and score you brownie points with your marketing department).

Let's take a look at a second example.

Excel Ticker Symbol Webding Wingding Icon

In this table, I use Webdings (characters "p" and "q") to add an even clearer visualization to the data. How much more appealing is that!

Free Printable PDF For Your Office or Cubicle!

There are endless possibilities when you break out of the standardized conditional formats and incorporate icons into your data and charts. I personally use a cheat sheet I created some time ago and have it printed and hanging on my cubicle wall next to my computer. If you want a free PDF copy of my cheat sheet, you can sign up for my free newsletter and instantly gain access to my icon cheat sheet (shown at the beginning of this article) and all the other example files used in my blog post. Plus you'll get my best tips & hacks to improve as an analyst, emailed to you a couple of times a month (none of them are posted on this website, so it's completely new content).

Just click the green download button below and you can quickly sign up and get your printable cheat sheet!

       Already Subscribed? Click HERE to log-in to the "Example Files" section

     Already Subscribed? Click HERE to log-in to the "Example Files" section

 

How Do You Use Icon Fonts?

I quickly touched on a couple ways I use icon fonts to make my data look more professional and understandable. I would love for you to leave a comment below and describe how you are planning on using icon fonts in your next project. Your experience or thoughts will help the whole TSG community (including myself) get ideas on how to improve our work. Thanks for stopping by!

Chris "Macro" Newman

How To Get Office 2016 With A 365 ProPlus Account

$
0
0
Obtaining Office 2016 with 365 ProPlus Account

A Little Background

I was literally pulling out my hair trying to figure out how to get my hands on the new Office 2016 for my PC. I personally have an Office 365 ProPlus account and could not determine why when I hit the upgrade button, I just reinstalled Office 2013. For some reason, Microsoft decided to exclude this group of subscribers from the Office 365 launch. Not cool...

Luckily, I have a HUGE newsletter-base with super smart people who pointed me in the direction of how to upgrade to Office 2016 right now instead of waiting until the February 2016 release date (like all the non-365 users). Since this isn't (in my opinion) visually documented too well on the web, I decided to document how to tweak your Admin settings so you too can bypass all the hair pulling and get your download now!

The Steps To Download Office 2016 with ProPlus

Step 1: Login to Office 365 (www.office.com) and go to your Admin Settings

Download Office 2016 with 365 ProPlus Account

Step 2: In the left pane, expand the Service Settings group

Step 3: Click the Updates option

First Release Setting Office 365

Step 4: You will need to switch your selected option button from Standard to Entire Organization or Select People

First Release Setting Office 365

Step 5: Go back to the main Office 365 page and click the Install hyperlink

Download Office 365 ProPlus version

Step 6: Look at that! You now how the option to download either Office 2013 OR Office 2016. That's much better :) 

Oh yeah, I was so excited, I almost forgot to tell you what to do.....close out of any Office programs you may have opened and click the Download button.

Download Office 365 ProPlus version

Hope That Helps!

I really hope you were able to follow along and you are now able to download Office 2016. Let me know in the comments section if this worked for you, or if you have any insight as to why Microsoft decided not to roll out Office 2016 to us ProPlus users until February 2016.


Excel Weaknesses: A Wishlist For Much Needed Improvements

$
0
0
Ways To Improve Excel Features

As Microsoft continues to persuade people to sign up for their Office 365 subscription in lieu of purchasing individual copies of Office, I am hoping that the Office team moves towards sending out more updates on a regular basis (similar to how Google does with their Chrome browser).

With this in mind, I wanted to take the time to air some of my grievances with Excel. While Excel is an awesome program and the Microsoft team continues to develop amazing updates, it seems like there are a bunch of little tweaks they could make that would go a long ways in helping us daily users become more efficient.  Here is my current list:

1. The Concatenate Function

One of the functions that always has annoyed me is the CONCATENATE function. It only accepts individual cell addresses instead or range references. For example =CONCATENATE(A1:C1) is NOT valid, while =CONCATENATE(A1,B1,C1) is. In my mind, this function is useless, since writing =A1&B1&C1 is much quicker.

Oh, and adding an optional delimiter input would be a nice touch too :)

2. Case Sensitive Cell Formatting

I love using dates as my headers for months. What really annoys me is you can't make a cell format for JAN. You would think by using "MMM" the formatting would capitalize the three-letter abbreviation for the month....but it doesn't. I wish Cell Formatting was case sensitive so "MMM", "mmm", "Mmm" each would output different formats.

3. Updated Userform/ActiveX controls designs (they are ugly!)

If you have ever seen an Office userform, you might think it was created a long time ago...we are talking about 1990s old! It would be great if Microsoft could either update the appearance of the whole suite of userform and ActiveX controls or add more customizing capabilities so we can bring them up to date ourselves.

4. Center Across Ribbon Button

It has been well documented that people should stay away from merging cells and use Excel's Center Across functionality. So why don't we add a button right below Merge & Center for Center Across? There's even room for it!

Center Across Instead of Merge & Center

5. Unhide Multiple Worksheets

Why can we only unhide one worksheet at a time? At least let us use the Ctrl key to select multiple sheet names from the list.

6. Ability to Remove Cell Styles

Have you ever received a file with (literally) thousands of Cell Styles stored in it? This can cause errors in your spreadsheet and makes the file size HUGE. So why can't we just have a button that lets us reset/remove all these useless things?!

Does anybody even use cell styles anyways?

7. Paste Special Row Height

Why can we paste special column width but not row height?

8. Custom/More Icons in the QAT

Have you ever been frustrated when you spend a bunch of time creating this super awesome macro and then when you go to add it to your Quick Access Toolbar, you can't seem to find an icon that makes sense? You then cycle through the 30-some icons over and over again.....then you just say screw it and pick the smiley face.

It would be nice to have the ability to upload our own icons or at least have the ability to call any of the icons from the Microsoft Icon Library.

Also, it would be nice if we didn't have to have those default green circle icons for the features that didn't make the ribbon cut so they don't have their own unique icon. How are we suppose to tell one green button from another?

 

9. Custom VBA Functions Recalculate Reliability

I would love to use custom VBA functions within my spreadsheets, but I am always scared to use them because I never know if they will automatically recalculate when changes occur to my numbers. I know you can write code to make the function volatile, but I always seem to have problems getting it to recalculate every time.

10. Turn Off Page Breaks

I understand the concept behind the page break indicators, but they really annoy me. They annoy me some much, that I have a dedicated macro for turning them off in my QAT. I wish there was an option where I could permanently turn off page breaks so I never have to see them again!

11. Tabbing In Text Boxes = Too Long

I absolute love to use text boxes to add instructions for my workbooks. One thing I can't comprehend is why when you TAB inside a text box, it equates to 28 spaces (yes, I took the time to count out the spaces just for this article). I wish tabbing was a bit more reasonable...maybe around 4 spaces for each tab? Just a thought :)

12. ENTER Key Disabled Inside Text Boxes

Why won't the ENTER key on your keyboard's 9-digit number pad function to go to a new line inside a text box????

13. Inserting Copied Rows Multiple Times In A Row

This also occurs while copy/inserting entire columns, but I get very frustrated when I need to copy 3 specific rows and insert them into the middle of my spreadsheet multiple times. Excel will only let you insert copied rows once, then you have to re-copy the rows and repeat. This can be super time consuming!

 

Time To Air Your Own Grievances!

Now that I've laid out my own list of wishes, it's time for you to share yours! Leave a comment below and I might even add it to the article list! Hopefully one day some Microsoft developers stumble across this article as they search for new ideas to improve Excel (you never know, it could happen). I look forward to reading through your ideas!

[UPDATE] Microsoft Now Has A Website For This!

As of November 2015, Microsoft has set up a UserVoice website solely dedicated to gauging the popularity of feature requests for Excel. This leads me to believe that the Excel developers are planning to start releasing added features on a more frequent basis now that they have a large subscriber base through Office 365. I've added some of the Excel weaknesses I'd like to see addressed to the site, so if you have a couple minutes adds some votes to what I've posted so we can get these things fixed!

Here are links to my suggestions:

 

Adding Bullet Points To Your Excel Spreadsheet Cells & Text Boxes

$
0
0
Insert Bullet Points Into Microsoft Excel Spreadsheet

I've been using bullet points inside Excel A LOT as of late and I thought I would share the many different ways you can insert those nifty little bullets. I have mainly been inserting bullet points inside text box objects within my "Instructions" pages (tabs), but I will list out some ways you can insert bullet points directly into your spreadsheet as well.

Within A Cell

1. Keyboard Shortcut: Alt + 7 (number must be from your number pad) 

2. Keyboard Shortcut: Alt + 0149

3. Copy and paste the below bullet point into your spreadsheet:

• 

4. Use re-sized cells and Icon Fonts (ie Wingdings, Webdings, etc...)

Add Bullet Points With Wingdings Webdings

5. Use a Cell Format rule (copy the following into the Type field:  "•  @" ). You can add spaces before the bullet point in the format rule to add an indentation.

Excel Spreadsheet Cell Format Rule For Bullets

Inside  A Text Box Object

Within a text box, you have a more straight-forward option to add bullet points. Here are the steps to get them inserted.

  1. Right-click in textbox
  2. Select Bullets
  3. Take your pick of any of the presets or customize your bullet points further by clicking Bullets and Numbering
Add Insert Bullet Points Into Excel Text Box

Now You Can Stay Organized!

Bullet points are a great way to make your lists and steps easier to read. My favorite out of the bunch is definitely the Alt+7 keyboard shortcut and it will definitely impress your co-workers when you magically make bullet points appear on the fly.

If there are any other good ways to insert bullet points, feel free to let me know in the comments section below. I would love to continue to add to this list and make it more comprehensive.

Shortcut To Switch Back And Forth Between Two Excel Worksheet Tabs

$
0
0
Mimic Alt + Tab Keyboard Shortcut Spreadsheets Excel

Is There An ALT-TAB Excel Equivalent?

One of my all-time favorite keyboard shortcuts is ALT + TAB. This simple keyboard combination lets you toggle back and forth between the current program window and the last program window you were viewing. It is extremely handy when you are trying to verify information between two sources or simply trying to multi-task. I also love this shortcut because every single PC user finds it useful, it is by no means a niche shortcut.

Since 95% of my world consists of interacting with Excel worksheets, I was extremely upset when I couldn't find any trace of a similar shortcut to flip back and forth between two Excel tabs that I was analyzing. I searched high and low, but could only find two worksheet navigating keyboard shortcuts: 

  1. CTRL + PAGE UP
  2. CTRL + PAGE DOWN

The problem with these shortcuts is they only navigate through the order of your tabs so you would have to key them 7 times to get from tab #2 to tab #9 and at that point you might as well grab a hold of your mouse.

Introducing ALT + ` (acute)

Since a shortcut to flip between Excel tabs didn't seem to exist, I set out to devise a solution for my dilemma. What I was able to come up with is the most impactful piece of VBA code I've written for myself to-date....And I am going to share it with you, NO STRINGS ATTACHED! 

With my proposed solution, you will be able to use the keyboard shortcut ALT+` (the acute sign is right above the TAB key on your keyboard) with Excel worksheet tabs as you would using ALT + TAB for program windows. I have named this amazingly useful piece of code: TabBack.

Adding The TabBack Macro Code

The following will show you step-by-step how to add the VBA code to your Personal Macro file so that you will always have this shortcut available to you while running Excel. 

Creating A Personal Macro File

First, if you have never triggered Excel to create a Personal Macro file you will need to do so. Here are the steps for creating it:

  1. Go to the View Tab
  2. Click the Macro button drop down and select Record Macro...
  3. In the Store Macro In drop down select Personal Macro Workbook
  4. Click OK
  5. Click a cell on your spreadsheet
  6. Go back to the Macro button drop down and select Stop Recording
How To Create Excel Personal Macro Workbook.png

That's it! Excel has now created a Personal Macro file that will automatically open in the background every time you launch your Excel application. Now let's paste in the code so you can add this awesome "tab back" functionality.

First you will need to launch your Visual Basic Editor while inside Excel. You can do this by using the keyboard shortcut ALT + F11.

Insert The ThisWorkbook Code

First, you will need to add an event triggered macro at the workbook-level of your Personal Macro workbook. This will ensure every time you open Excel, the TabBack shortcut will be available to you.

  1. Expand the PERSONAL.XLSB project tree by clicking the plus sign next to the file name in the Project Explorer (use keyboard shortcut CTRL + R to view if it is now showing)
  2. Inside the Microsoft Excel Objects folder, double-click on the ThisWorkbook object
  3. Paste in the corresponding VBA code from this article into the ThisWorkbook object coding area
Switching Back And Forth Between Last Worksheet Excel Tab

You can copy the code shown in the above screenshot here:

Private Sub Workbook_Open()
'PURPOSE: Run code when this workbook is opened
'SOURCE: www.TheSpreadsheetGuru.com

'Run the TabBack macro
  Call TabBack_Run

End Sub

Insert The Module Code

Next, you will need to add some VBA code into a module. This is where you will set the keyboard shortcut combination and execute the action of toggling between spreadsheet tabs.

  1. In the Modules folder, double-click on the Module named Macro1. You will need to rename Macro1 to TabBack (use the keyboard shortcut F4 while Macro1 is selected to view the Properties window pane).
  2. Double-Click the TabBack module name in the Project Window
  3. Delete any miscellaneous code that was recorded when you initially created the Personal Macro workbook
  4. Paste in the corresponding VBA code from this article into the TabBack Module coding area
Flip Back And Forth Excel Spreadsheet Tabs

You can copy the code shown in the above screenshot here:

Dim TabTracker As New TabBack_Class

Sub TabBack_Run()
'PURPOSE: Initiate Tab tracking and shortcut key trigger
'SOURCE: www.TheSpreadsheetGuru.com

'Enable TabTracker class
  Set TabTracker.AppEvent = Application
  
'Call ToggleBack macro when user keys alt + `
  Application.OnKey "%`", "ToggleBack"

End Sub

Sub ToggleBack()
'PURPOSE: Go Back to Previous Worksheet
'SOURCE: www.TheSpreadsheetGuru.com

With TabTracker
  On Error Resume Next
  Workbooks(.WorkbookReference).Worksheets(.SheetReference).Activate
  On Error GoTo 0
End With

End Sub

Insert The Class Module Code

In this final section, you will need to create a Class Module

  1. Right-click on the Module folder
  2. Go to Insert and select Class Module
Toggle To Last Tab Visited In Spreadsheet Microsoft Excel

Once you have a new Class Module create, there are a few more steps you will need to do.

  1. In the Class Modules folder, double-click on the Class named Class1. You will need to rename Class1 to TabBack_Class (use the keyboard shortcut F4 while Class1 is selected to view the Properties window pane).
  2. Double-Click the TabBack module name in the Project Window
  3. Paste in the corresponding VBA code from this article into the TabBack_Class Class Module coding area
  4. Save your Personal Macro file
Keyboard Shortcut Tab Back To Previous Spreadsheet

You can copy the code shown in the above screenshot here:

Public WithEvents AppEvent As Application
Public SheetReference As String
Public WorkbookReference As String

Private Sub AppEvent_SheetDeactivate(ByVal Sh As Object)
'PURPOSE: Store active worksheet information before leaving it
'SOURCE: www.TheSpreadsheetGuru.com

  WorkbookReference = Sh.Parent.Name
  SheetReference = Sh.Name
  
End Sub

Private Sub AppEvent_WorkbookDeactivate(ByVal Wb As Workbook)
'PURPOSE: Store active worksheet information before closing workbook
'SOURCE: www.TheSpreadsheetGuru.com

  WorkbookReference = Wb.Name
  SheetReference = Wb.ActiveSheet.Name
  
End Sub

Running The TabBack Macro

Now that you have all your VBA code pasted in and saved, you can go ahead and exit out of the Visual Basic Editor. In order to start using the TabBack keyboard shortcut, you simply need to restart Excel.

Now all you need to do is practice your ALT + ` finger positions. I find that using your thumb for the ALT key and your middle finger for the Acute key is the most comfortable.

VBA Coding Not Your Thing?

I can understand if all this VBA coding stuff seems scary or too time-consuming to fiddle around with. That is why I went ahead and coded an Excel add-in file so you can simply install it and start using tab toggling functionality. I am making this add-in a free download to my email subscribers. So if you are not subscribed to my Excel tips newsletter, click the button below and quickly sign yourself up! You'll then be able to easily download this article's add-in file along with a whole bunch of awesome example files that correspond with the tutorials I have written.

  Already Subscribed? Click HERE to log-in to the "Example Files" section

Already Subscribed? Click HERE to log-in to the "Example Files" section

 

Room For Improvement?

I am in no way very experienced with creating Classes in VBA. If you see something in my code that is missing or would improve the functionality, please let me know in the comments section so I can make any adjustments. I have been using this code for a while now and haven't run into any issues to-date, but as with all coding I'm sure there are ways to improve it. Let me know your thoughts!


The VBA Guide To Named Ranges

$
0
0
Blog Post Banner (hdr).png

What Is A Named Range?

Creating a named range allows you to refer to a cell or group of cells with a custom name instead of the usual column/row reference. The HUGE benefit to using Named Ranges is it adds the ability to describe the data inside your cells. Let's look at a quick example:

Can you tell if shipping costs are charged with the product price?

  1. = (B7 + B5 * C4) * (1 + A3)
  2. =(ShippingCharge + ProductPrice * Quantity)  * (1 + TaxRate)

Hopefully, you can clearly see option number TWO gives you immediate insight to whether the cost of the products includes shipping costs. This allows the user to easily understand how the formula is calculating without having to waste time searching through cells to figure out what is what.

How Do I Use Named Ranges?

As a financial analyst, I play around with a bunch of rates. Examples could be anything from a tax rate to an estimated inflation rate. I use named ranges to organize my variables that either are changed infrequently (ie Month or Year) or something that will be static for a good amount of time (ie inflation rate). Here are a list of common names I use on a regular basis:

  • ReportDate
  • Year
  • Month
  • FcstID
  • TaxRate
  • RawData

Creating Unique Names On The Fly

It is super easy to create a Named Range. All you have to do is highlight the cell(s) you want to reference and give it a name in the Name Box. You name cannot have any spaces in it, so if you need to separate words you can either capitalize the beginning of each new word or use an underscore (_). Make sure you hit the ENTER key after you have finished typing the name to confirm the creation of the Named Range.

As a side note, any Named Range created with the Name Box has a Workbook scope. This means the named range can be accessed by any worksheet in your Excel file.

Name Box.png

 

Creating Names With The "Name Manager"

If you want to customize your named ranges even more, you can open up the Name Manager (Formulas tab > Defined Names group > Name Manager button) to edit and create new named ranges.

I won't go into great detail in this article, but know that with the Name Manager you can

  1. Change the name of an existing Named Range
  2. Change the reference formula
  3. Specify the scope (what worksheets the name can be accessed from)

On To The VBA

Now that you have had a brief overview on Named Ranges, lets dig into some VBA macros you can use to help automate the use of Named Ranges.

Add A Named Range

The below VBA code shows ways you can create various types of named ranges.

Sub NameRange_Add()
'PURPOSE: Various ways to create a Named Range
'SOURCE: www.TheSpreadsheetGuru.com

Dim cell As Range
Dim rng As Range
Dim RangeName As String
Dim CellName As String

'Single Cell Reference (Workbook Scope)
  RangeName = "Price"
  CellName = "D7"
  
  Set cell = Worksheets("Sheet1").Range(CellName)
  ThisWorkbook.Names.Add Name:=RangeName, RefersTo:=cell


'Single Cell Reference (Worksheet Scope)
  RangeName = "Year"
  CellName = "A2"
  
  Set cell = Worksheets("Sheet1").Range(CellName)
  Worksheets("Sheet1").Names.Add Name:=RangeName, RefersTo:=cell


'Range of Cells Reference (Workbook Scope)
  RangeName = "myData"
  CellName = "F9:J18"
  
  Set cell = Worksheets("Sheet1").Range(CellName)
  ThisWorkbook.Names.Add Name:=RangeName, RefersTo:=cell


'Secret Named Range (doesn't show up in Name Manager)
  RangeName = "Username"
  CellName = "L45"
  
  Set cell = Worksheets("Sheet1").Range(CellName)
  ThisWorkbook.Names.Add Name:=RangeName, RefersTo:=cell, Visible:=False

End Sub

Loop Through Named Ranges

This VBA macro code shows how you can cycle through the named ranges within your spreadsheet.

Sub NamedRange_Loop()
'PURPOSE: Delete all Named Ranges in the Active Workbook
'SOURCE: www.TheSpreadsheetGuru.com

Dim nm As Name

'Loop through each named range in workbook
  For Each nm In ActiveWorkbook.Names
    Debug.Print nm.Name, nm.RefersTo
  Next nm
  
'Loop through each named range scoped to a specific worksheet
  For Each nm In Worksheets("Sheet1").Names
    Debug.Print nm.Name, nm.RefersTo
  Next nm

End Sub

Delete All Named Ranges

If you need to clean up a bunch of junk named ranges, this VBA code will let you do it.

Sub NamedRange_DeleteAll()
'PURPOSE: Delete all Named Ranges in the ActiveWorkbook (Print Areas optional)
'SOURCE: www.TheSpreadsheetGuru.com

Dim nm As Name
Dim DeleteCount As Long

'Delete PrintAreas as well?
  UserAnswer = MsgBox("Do you want to skip over Print Areas?", vbYesNoCancel)
    If UserAnswer = vbYes Then SkipPrintAreas = True
    If UserAnswer = vbCancel Then Exit Sub

'Loop through each name and delete
  For Each nm In ActiveWorkbook.Names
    On Error GoTo Skip
    
    If SkipPrintAreas = True And Right(nm.Name, 10) = "Print_Area" Then GoTo Skip
    
    nm.Delete
    DeleteCount = DeleteCount + 1

Skip:
    
  Next
  
'Reset Error Handler
  On Error GoTo 0
    
'Report Result
  If DeleteCount = 1 Then
    MsgBox "[1] name was removed from this workbook."
  Else
    MsgBox "[" & DeleteCount & "] names were removed from this workbook."
  End If

End Sub

Delete Named Ranges with Error References

This VBA code will delete only Named Ranges with errors in them. These errors can be caused by worksheets being deleted or rows/columns being deleted.

Sub NamedRange_DeleteErrors()
'PURPOSE: Delete all Named Ranges with #REF error in the ActiveWorkbook
'SOURCE: www.TheSpreadsheetGuru.com

Dim nm As Name
Dim DeleteCount As Long

'Loop through each name and delete
  For Each nm In ActiveWorkbook.Names
    On Error GoTo Skip
    If InStr(1, nm.RefersTo, "#REF!") > 0 Then
      nm.Delete
      DeleteCount = DeleteCount + 1
    End If
Skip:
    
  Next
  
'Reset Error Handler
  On Error GoTo 0
  
'Report Result
  If DeleteCount = 1 Then
    MsgBox "[1] errorant name was removed from this workbook."
  Else
    MsgBox "[" & DeleteCount & "] errorant names were removed from this workbook."
  End If
  
End Sub

Anything Missing From This Guide?

Let me know if you have any ideas for other useful VBA macros concerning Named Ranges. Or better yet, share with me your own macros and I can add them to the article for everyone else to see! I look forward to reading your comments below.

How Do I Modify This To Fit My Specific Needs?

Chances are this post did not give you the exact answer you were looking for. We all have different situations and it's impossible to account for every particular need one might have. That's why I want to share with you: My Guide to Getting the Solution to your Problems FAST! In this article, I explain the best strategies I have come up with over the years to getting quick answers to complex problems in Excel, PowerPoint, VBA, you name it

I highly recommend that you check this guide out before asking me or anyone else in the comments section to solve your specific problem. I can guarantee 9 times out of 10, one of my strategies will get you the answer(s) you are needing faster than it will take me to get back to you with a possible solution. I try my best to help everyone out, but sometimes I don't have time to fit everyone's questions in (there never seem to be quite enough hours in the day!).

I wish you the best of luck and I hope this tutorial gets you heading in the right direction!

Chris "Macro" Newman :)

Christmas Expense & Budget Tracker Excel Template 2015 (Free!)

$
0
0
Christmas Holiday Present Expense Tracker Spreadsheet Template

It's That Time Of Year Again!

If you love analyzing numbers (and chances are if you are a fan of this website you do), then I am sure you can relate that your skill of tracking digits carries over to your home life as well. I am so excited to share with you one of my personal Excel trackers that I use to keep a close eye on my Christmas present spending. It comes complete will a nifty Christmas-themed dashboard so you can instantly know how you are doing throughout the holiday season. I think you will enjoy having this simple tracking spreadsheet and hopefully you'll be able to keep your spending under control this Christmas season!

An Awesome Status Dashboard

Dashboards seem to be all the rage currently and it's very easy to understand why -- they can instantly tell you the story behind your data. Below is what my Christmas expense tracking template dashboard looks like.

Christmas Present Spending Dashboard Excel Spreadsheet Budget

Two Simple Tables To Track Your Progress

I like keeping things simple, because who really wants to spend all their time creating a bunch of data points that aren't really that important. With my present tracking template you have two tables to populate.

The first one (on the left) lets you set a budget for each one of your friends & family members who will be receiving a Christmas gift from you this year.

The second table (on the right) is where you will record how much you have spent on each person. 

Both of these tables feed into your dashboard, allowing you to have a visualization of your data in real-time!

Christmas Budget Purchase Expense Spending Tracking Spreadsheet

All Graphics Made With Only Excel Shapes

OK...this may not be a cool feature, but I just wanted to highlight that you can make beautiful icons and graphics without super expensive software. And it's REALLY EASY! If you are curious how the any of the graphics are made, you can simply unprotect the dashboard (Review Tab > Unprotect Sheet -- there is no password) and see for yourself how they were created. Below is a breakdown of how I made the reindeer.

Creating Christmas Excel Graphics

Get Yourself A Copy Now!

It is super easy to download this Excel template. You will just need to provide me with your email address within the form below and the file download will be instantly sent to your inbox. The email subject line should say "You Got Christmas Spending Tracker!"

While I am offering this template for free, I inevitably always get people who want to chip in a few bucks as a thank you. So it's up to you, you can keep the price at $0 or pay whatever you want :) You have the option to pay via credit card or PayPal.

...

What Do You Think?

As this is a personal template, I would love to get you input on how to make it better. Also, if you notice any bugs please let me know in the comments section below. I will always update this post with the latest version as well as record what the latest version is (see above). I look forward to your feedback :)

Have a Merry Christmas!!!

Chris "Macro" Newman

Viewing all 117 articles
Browse latest View live


Latest Images