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

VBA Code to Lighten or Darken Fill Colors in Excel

$
0
0
VBA Macro Code Shade Color Dark Light RGB HSV

I've been on a mission the past two weeks to craft a pair of macros to lighten and dark a cell fill color. The main reason I wanted to do this was to create complimentary colors for my spreadsheet formats on the fly given a specific color. Here is an example of how I would typically use this:

Excel Shaded Heading Example Via VBA Macro Code

Color Codes Can Be Complicated!

In my pursuit to craft this code, I have had to do a TON of research on color codes and how to manipulate them. I was familiar with RGB and HEX, but had never delved into HSL and HSV.  There are basic premises to each of these color coding systems, but when you start manipulating hues, saturations, the brightness, adding 16-base digits......I could go on, but I think you get the picture. It can get EXTREMELY complicated!

I Found Some Solutions!

After days of digging through countless forum posts (mostly on StackOverflow) and pulling many follicles of hair out off my scalp, I was able to come up with two solutions.

And since I'm such a nice guy, I'm going to share them with you :)

Not Perfect, But Do The Trick

Now these solutions aren't 100% perfect, but I'm hoping some mathematicians can help tweak my logic a bit. Why aren't they perfect in my eyes? Well, in my mind if I run the "Lighten" macro and then run the "Darken" macro, I should end of with my exact original color. With both solutions I was able to write, the color ends up being slightly off (typically only noticeable if you check the RGB color code).

I won't be able to thank you enough if you have time to look through all the math and figure out a way to get the code so it can be reversed! It's just a little out of my skillset to solve at this time.

Solution 1: RGB Manipulation (My Preferred Macro)

I found the logic used in the Lighten macro below in some forum and for the life of me cannot find it again! So I apologize for not being able to credit anyone for the algorithm. I reversed the algorithm (who knew algebra class would come in handy one day!) to create the algorithm used in the darkening macro.

Like I mentioned before, these two macros can't be toggled macro in forth to "undo" a shade. The colors will be super close but not exact (not sure if it's a rounding thing or what). If you can solve the issue PLEASE let me know how to fix it in the comments section below and I will update this article.

Lighten Cell Fill By A Shade

Sub FillColor_Lighten()
'PURPOSE: Lighten the cell fill by a shade while maintaining Hue (base Color)
'SOURCE: www.TheSpreadsheetGuru.com

Dim HEXcolor As String
Dim cell As Range
Dim Lighten As Integer
Dim r As Integer
Dim g As Integer
Dim b As Integer
Dim r_new As Integer
Dim g_new As Integer
Dim b_new As Integer

'Shade Settings
  Lighten = 3 'recommend 3 (1-16)

'Optimize Code
  Application.ScreenUpdating = False

'Loop through each cell in selection
  For Each cell In Selection.Cells
  
    'Determine HEX color code
      HEXcolor = Right("000000" & Hex(cell.Interior.Color), 6)
    
    'Determine current RGB color code
      r = CInt("&H" & Right(HEXcolor, 2))
      g = CInt("&H" & Mid(HEXcolor, 3, 2))
      b = CInt("&H" & Left(HEXcolor, 2))
    
    'Calculate new RGB color code
      r_new = WorksheetFunction.Round(r + (Lighten * (255 - r)) / 15, 0)
      g_new = WorksheetFunction.Round(g + (Lighten * (255 - g)) / 15, 0)
      b_new = WorksheetFunction.Round(b + (Lighten * (255 - b)) / 15, 0)
    
      'Debug.Print r_new, g_new, b_new
    
    'Change enitre selection's fill color
      cell.Interior.Color = RGB(r_new, g_new, b_new)
  
  Next cell

End Sub

Darken Cell Fill By A Shade

Sub FillColor_Darken()
'PURPOSE: Darken the cell fill by a shade while maintaining Hue (base Color)
'SOURCE: www.TheSpreadsheetGuru.com

Dim HEXcolor As String
Dim cell As Range
Dim Darken As Integer
Dim r As Integer
Dim g As Integer
Dim b As Integer
Dim r_new As Integer
Dim g_new As Integer
Dim b_new As Integer

'Shade Settings
  Darken = 3 'recommend 3 (1-16)

'Optimize Code
  Application.ScreenUpdating = False

'Loop through each cell in selection
  For Each cell In Selection.Cells
    
    'Determine HEX color code
      HEXcolor = Right("000000" & Hex(cell.Interior.Color), 6)
    
    'Determine current RGB color code
      r = CInt("&H" & Right(HEXcolor, 2))
      g = CInt("&H" & Mid(HEXcolor, 3, 2))
      b = CInt("&H" & Left(HEXcolor, 2))
    
    'Calculate new RGB color code
      r_new = WorksheetFunction.Round((r * 15 - 255 * Darken) / (15 - Darken), 0)
      g_new = WorksheetFunction.Round((g * 15 - 255 * Darken) / (15 - Darken), 0)
      b_new = WorksheetFunction.Round((b * 15 - 255 * Darken) / (15 - Darken), 0)
    
    'Change enitre selection's fill color
      On Error Resume Next
        cell.Interior.Color = RGB(r_new, g_new, b_new)
      On Error GoTo 0
  
  Next cell

End Sub

Solution 2: RGB to HSV Manipulation

So far this code doesn't work as well with certain colors as the first solution, but I am posting it in hopes that someone can save it.

The idea behind this is to convert the RGB color code into a HSV (hue, saturation, brightness value) code. Once in HSV, you can specifically target the "V" value while maintaining the hue and saturation, essentially allowing you to maintain the base color. Once you manipulated the HSV color code, you translate it back to RGB and apply it to your cell fill.

I pulled this logic together straight from a great article entitled Lode's Computer Graphic Tutorial - Light and Color.

Sub HSV_Shading()
'PURPOSE: To lighten or darken a cell fill color while maintaining Hue (base color)
'SOURCE: www.TheSpreadsheetGuru.com
'LOGIC SOURCE: http://lodev.org/cgtutor/color.html#The_HSL_Color_Model_

Dim HEXcolor As String
Dim cell As Range
Dim ShadeRate As Integer

'Rate You wish to lighten (darken)
  ShadeRate = 50 'I recommend 50 or 25 (Make negative to darken)

'Store ActiveCell to a variable
  Set cell = ActiveCell

'Determine HEX color code
  HEXcolor = Right("000000" & Hex(cell.Interior.Color), 6)
  
'Determine current RGB color code
  r = CInt("&H" & Right(HEXcolor, 2)) / 256
  g = CInt("&H" & Mid(HEXcolor, 3, 2)) / 256
  b = CInt("&H" & Left(HEXcolor, 2)) / 256
    
'********************
'Convert RGB to HSV
'********************
  maxColor = WorksheetFunction.Max(r, g, b)
  minColor = WorksheetFunction.Min(r, g, b)
  v = maxColor

  If maxColor = 0 Then
    s = 0
  Else
    s = (maxColor - minColor) / maxColor
  End If
  
  If s = 0 Then
    h = 0
  Else
    If r = maxColor Then
      h = (g - b) / (maxColor - minColor)
    ElseIf g = maxColor Then
      h = 2 + (b - r) / (maxColor - minColor)
    Else
      h = 4 + (r - g) / (maxColor - minColor)
    End If
    
    h = h / 6
    If h < 0 Then h = h + 1
  End If
    
'Output The HSV Color Code with adjustment rate
  h = Int(h * 255)
  s = Int(s * 255)
  v = Int(v * 255) + ShadeRate
    If v < 0 Then v = 0

'********************
'Conver HSV to RGB
'********************
  h = h / 256
  s = s / 256
  v = v / 256
  
  If s = 0 Then
    r = g
    g = b
    b = v
  End If

  h = h * 6
  i = Int(WorksheetFunction.RoundDown(h, 0))
  f = h - i
  p = v * (1 - s)
  q = v * (1 - (s * f))
  t = v * (1 - (s * (1 - f)))
  
  Select Case i
    Case 0: r = v: g = t: b = p
    Case 1: r = q: g = v: b = p
    Case 2: r = p: g = v: b = t
    Case 3: r = p: g = q: b = v
    Case 4: r = t: g = p: b = v
    Case 5: r = v: g = p: b = q
  End Select

'Output New RGB Color Code
  r = Int(r * 255)
  g = Int(g * 255)
  b = Int(b * 255)

'Change Cell Fill To New Color
  cell.Interior.Color = RGB(r, g, b)

End Sub

Any Other Ideas?

there were lots of algorithms floating around in many different coding languages. Let me know if you have a better or more efficient way of lightening or darkening a fill color while maintaining the essence of the color. I know there are simple ways to adjust the brightness of an RGB code by applying a percent to it, but I don't think the color outputs are visually appealing. I looking forward to your responses!


Excel PowerBall Lottery Simulator Spreadsheet

$
0
0
Microsoft Excel PowerBall Lottery Spreadsheet Simulation Game

With all the excitement over the $900 Million PowerBall Jackpot this past weekend, I thought it would be interesting to create an Excel-based simulator so I could pretend that I had money to blow on purchasing lottery tickets (I ended up buying 2 losing tickets, so it looks like I won't be retiring in my 20's....)

I busted this simulator out in 2 hours (thanks to a little dose of caffeine). So feel free to dig into the VBA logic and correct anything that may be wrong, but I am fairly confident it's performing as intended.

The basic premise of the simulator, is you tell it how much money you want to spend playing the lottery, pick some numbers, and then watch as you play the PowerBall lottery over and over until you run out of money. I'm not going to lie this simulator is both extremely addicting and filled with lot's of disappointment...kind of like the real thing!

Below is the simulation dashboard I came up with, and yes 100% of it was created in Excel (even the lottery icons)!

Inspiration for this simulator came from the LA Times website

Inspiration for this simulator came from the LA Times website

The Odds Are DEFINITELY Not In Your Favor

I think we all are aware that it is very hard to win the lottery, but I think it's sometimes hard to relate to really crazy odds like 1 in 11.6 million. So here are a few different ways at looking at the lottery odds: 

  1. Struck by lightning, while drowning (1 in 183 million)
  2. Killed by an asteroid strike (1 in 700,000)
  3. Have an IQ of 190 or greater (1 in 107 million)
  4. Attacked by a shark (1 in 11.5 million)
  5. Elected President of the United States (1 in 10 million)
  6. Getting struck by lightning (1 in 164,968)
  7. Being drafted by an NBA team (1 in 6.8 million)
  8. Becoming a movie star (1 in 1.5 million)
  9. Dating a supermodel (1 in 88,000)
  10. Being killed by a vending machine (1 in 112 million)

(Source: TheDenverChannel.com)

PowerBall Lottery Winnings/Odds

Below is a little info-graphic I created in Excel with the official statistics for the PowerBall Lottery drawing as of January 2016.

United States PowerBall Lottery Winning Odds

Download the Excel Simulator & Test Your Luck

If you want to download my PowerBall Lottery Simulator spreadsheet (fully unlocked), you can sign up for my free newsletter and instantly gain access to this file and any other of the many example files used in my blog posts. 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 own copy of the simulator spreadsheet!

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

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

 

Are You Able To Turn A Profit?

After playing around with this simulator for quite some time, I  came to the conclusion that I am not really that lucky. But I'm sure some of you are! Post a screenshot of your highest lottery winnings in the comments section below and who knows, maybe I'll give out a REAL prize for some of the top earners :) P.S. No CHEATING!!

Excel PowerBall Lottery Ticket Checker Spreadsheet

$
0
0
PowerBall Lottery Excel Spreadsheet Ticket Checker

Checking Lottery Picks = Painful

With the new trend of ginormous lottery jackpots, there seem to be more and more groups of people coming together to purchase as many tickets as possible. Going through and manually checking the numbers can be quite a pain and there is a high possibility you might miss a winning combination.

With this Excel-powered spreadsheet, you can type in all your lottery ticket picks and automatically get fed winning numbers once the lottery balls have been picked. I'll provide a little bit of how the spreadsheet is setup and then you can download this Excel file for free and use it to analyze the next time your office pulls together $500 bucks for a chance at living the good life.

The PowerBall Dashboard

Let's tackle the cool part first. The dashboard is where you'll go to see if you had any wining tickets. There are three sections containing user inputs:

  1. Enter the Jackpot amount
  2. Add the PowerBall lottery numbers that were picked the night of the drawing
  3. Select the Power Play Multiplier from the drop down menu

Once you have entered the winning numbers, you will instantly see if you have won any money (hopefully, it is more than $8...)

PowerBall Lottery Calculator Excel Spreadsheets Dashboard Model

Enter Your Purchased Tickets

Unfortunately, there is no way that I could dream up that would get Excel to scan all your lottery numbers and load them into this model. So this is where some dreaded manual work comes into play.

You can enter in all your numbers into the table (order doesn't matter except for the PowerBall number needs to be in the PowerBall column). Make sure that all your data is within the table indicator, designated by the tiny blue right-angle icon in the bottom right-hand corner (shown in the screenshot below). That way the lottery dashboard and all the formulas will pick up your entire data set.

Input Powerball Lottery Picks Into Excel Table

Power Play Multiplier [Optional]

Some people like to pay an extra $1 to the lottery ticket price and gain the Power Play Multiplier. This allows you to multiply your winnings by a specific amount. If you have tickets that include the Power Play option, simply select 'Yes' in the drop down menu within the Power Play table column.

What Are The Odds?

Excel Infographic PowerBall Lottery Odds

Within the Excel Spreadsheet, I also have a worksheet dedicated to showing you just how bad your odds are. Also, within the table are the payout combinations.

You can see that the payout really isn't that much until you start matching 5 out of the 6 numbers.

I use this table in the spreadsheet to lookup the payouts while calculating the winnings. So if for some reason down the road the payouts change, you can just update the table amounts and keep on using this nifty spreadsheet tracker.

Error Prevention

While building any sort of model (even if it's just for fun), you should always build in measures to prevent user errors. I have used a couple of Excel's native features to prevent data input errors while building this spreadsheet.

  • Conditional Formatting - To display duplicate values within a row. You may only have 6 unique numbers to make up your picks
  • Data Validation - To ensure your numbers are within the range of possibility. As of this writing, the 5 normal picks can be a number from 1 to 69. The PowerBall number can be any number between 1 and 26.
  • Password Protection - I went ahead and password protected the PowerBall Lottery Calculator's dashboard to prevent accidents. There is no password to unlock the spreadsheet, you simply just need to click on the Remove Protection button within the Review Ribbon Tab.
PowerBall Lottery Calculator Excel Spreadsheets Error Prevention

Download the PowerBall Ticket Checker Spreadsheet

If you want to download this PowerBall Lottery ticket checker spreadsheet (fully unlocked), you can sign up for my free newsletter and instantly gain access to this file and any other of the many example files used in my tutorials. Plus you'll get my best tips & hacks to improve yourself as an analyst, which will be emailed to you a couple 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 own copy of the spreadsheet!

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

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

 

Have You Ever Won?

I would love to see if any visitors have actually won the lottery! How much did you win? What did you spend it on? Let me know your lottery story in the comments section below. 

I look forward to reading your lottery experience :)

Adding Tickmark Indicators To Your Excel Analysis Comments

$
0
0
Adding Indicators To your Analytical Story in Excel Spreadsheets

We Visualize Data, Why Not Commentary?

Have you ever heard that age old phrase, "A picture is worth a thousand words"?

My guess is you probably have and you intuitively know visuals leave more of an impact than dry-heaving numbers onto a page and handing it to your manager.

I think most people who provide data analytics understand the power of charting their data to tell their story, but what I see overlooked time and time again is the lack of visualization with the commentary that compliments those beautiful charts. 

Today, I am going to show you how to easily add indicators to your commentary so your audience (ie the decision-makers) already has the right state of mind before reading a single letter of your comments. This will tremendously help them comprehend your analysis and score you "brownie points", because they will be able to do it in a fraction of the time as well!

The Power Of The Indicator

BONUS TIP: You can add bullet points to a cell by using the shortcut key ALT+7 (use the seven on the number pad not main keyboard)

BONUS TIP: You can add bullet points to a cell by using the shortcut key ALT+7 (use the seven on the number pad not main keyboard)

Above is an example of some commentary that describes the story of the bar chart. One might think at first glance because the numbers are increasing over time, that the metric is performing well. However, after reading through the commentary you can come to the conclusion that the company is drastically headed in the wrong direction.

Here's how it would look if you added some simple little indicators to go along with each comment...

Chart With Tickmark Indcators Microsoft Excel Spreadsheet

By literally adding 2 characters, the perspective of glancing over this report immediately changes and your audience knows that this area has some problems and are likely to spend some time looking into the area of this business.

How I Add Indicators To My Comments

There are a TON of ways you could approach adding indicators to your comments.

The first way that jumps from your mind might be to use the stoplight icons within Excel's built-in Conditional Formatting in combination with some sort of formula tied to your data. Your logic might look something like below, were you can simply enter in a "g", "y", or "r" to get your desired colored tickmark.

Excel Conditional Formatting Stoplight Icons

This methodology works fine, however I personally like to have complete control over my formatting options. My personal preference is to use an icon font such as Webdings or Wingdings and combine that with some conditional formatting to change the font color based on the icon font character.

Here's a cheat sheet for all the icon fonts you have access to within Microsoft Office.

To help you visualize how this concept works. Let's say I want to use triangles within the Wingdings 3 font  to indicate good/bad comments. Here are the steps you would need to take to manually incorporate this:

  1. Add the regular character that corresponds to the symbol you want to display in front of your text (see my Character Map for reference)
  2. Highlight your symbol character and give it a specific font color. 
  3. Highlight the symbol character, navigate to the Home Tab, and change the font name to your desired icon font (in my example below, I use Wingdings 3)
Adding Icon Font To Text In Excel Spreadsheet Cell

How To Automate This With A VBA Macro

Now if you plan on doing this on a regular basis, you are going to love what I am about to share with you in this section. Below is my personal VBA code, where you can cycle through three different indicators at the click of a button!

Take a look at how easy it can be:

VBA Macro To Add Indicator Tickmark to Text

Retaining Bold Characters

The one super-cool part about this macro is it remembers characters that are bold. A classic format that I use in the "Real World" at my day job looks as follows:

VBA Code To Add Symbol To Text

When the code line cell.FormulaR1C1 = Right(cell.Text, Len(cell.Text) - 2) is executed, the entire text losses any bold characters that may have been formatted. To counteract this, I use an array (ie list) variable to record the position of each bold character prior to any changes. Then once the modifications are made, the code cycles through the list of positions and bolds the specific characters to their original format.

Enough of the nerdy stuff....here is the actual code for you to automate this process!

Hopefully, my code below is commented well enough to where you can easily modify it with your own symbols & colors with little effort.

The VBA Code

Sub TextTickmark_Triangle()
'PURPOSE: Add Triangle Tickmark Indicator to beginning of selection text
'SOURCE: www.TheSpreadsheetGuru.com

Dim cell As Range
Dim TextFont As String
Dim TickChar As String
Dim TickColor As Long
Dim BoldArray() As Variant
Dim BoldOffset As Integer
Dim y As Long
Dim x As Long

'Determine Direction and Color
   If TypeName(Selection) <> "Range" Then Exit Sub
  
'Loop through each cell in selection
  For Each cell In Selection.Cells
        
  'Store font type
    TextFont = cell.Characters(1, 1).Font.Name
  
  'Determine which color/type of tickmark to add
    If TextFont = "Wingdings 3" Then
      Select Case Left(cell.Text, 2)
        Case "p "
          TickColor = -16776961 'red
          TickChar = "q "
          BoldOffset = 0
        Case "q "
          TickColor = 49407 'Orange
          TickChar = "u "
          BoldOffset = 0
        Case "u "
          TickColor = 0
          TickChar = "" 'reset
          BoldOffset = -2
        Case Else
          Exit Sub
      End Select
    Else
      TickColor = -11489280 'green
      TickChar = "p "
      BoldOffset = 2
    End If
    

    'Reset out Bold Character array
      Erase BoldArray
      ReDim BoldArray(0)
      y = 0
      
    'Record Any Bold Characters Within Text
      For x = 1 To Len(cell.Text)
        If cell.Characters(x, 1).Font.FontStyle = "Bold" Then
          ReDim Preserve BoldArray(y)
          BoldArray(y) = x + BoldOffset
          y = y + 1
        End If
      Next x
    
    'Remove Previous Tickmark from Text
      If TickChar <> "p " Then
        cell.Font.Color = cell.Characters(3, 1).Font.Color
        cell.Font.Name = cell.Characters(3, 1).Font.Name
        cell.FormulaR1C1 = Right(cell.Text, Len(cell.Text) - 2)
      End If
      
    'Add Tickmark
      If TickChar <> "" Then
        cell.FormulaR1C1 = TickChar & cell.Text
        cell.Font.FontStyle = "Normal" 'Ensure text is not bold (for now)
        
        With cell.Characters(Start:=1, Length:=1).Font
          .Name = "Wingdings 3"
          .Color = TickColor
        End With
      End If
    
    'Re-Bold Any Text previously bolded
      If Not IsEmpty(BoldArray(0)) Then
        For x = LBound(BoldArray) To UBound(BoldArray)
          cell.Characters(Start:=BoldArray(x), Length:=1).Font.FontStyle = "Bold"
        Next x
      End If
      
  Next cell

End Sub

Learn More With This Example Workbook

I have created a sample workbook with some of the methodologies described in this article (including some conditional formatting examples). 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 tips 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

 

Other Articles You May Like

3 Creative Ways to Use Special Fonts to Enhance Your Excel Spreadsheets [BradEdgar.com]

Wingdings & Webdings Font Icon Character Map [TheSpreasheetGuru.com]

Correcting Shape Assigned Macro Links After Copying Worksheet VBA

$
0
0
Fix Assigned Macro Copy Workbook Name Excel Spreadsheets VBA

Transferring VBA Through Worksheet Objects

The easiest way to copy over VBA code while copying your worksheets into a new workbook is to store your VBA macros within the worksheet itself instead of the typical Modules that most people use. While it is possible to copy Modules from one workbook to another, it adds another layer of VBA coding that is much more of a hassle than storing your code within a Worksheet Object.

The one problem with this, however, arises when you have macros assigned to be triggered by on-sheet buttons (ie shapes). What happens when you copy a worksheet, is the macro link still points back to the original workbook and not the new one. Here is an example showing what happends when I copied a worksheet with VBA code stored in it from Book1 into Book2:

As you can see in the above screenshot, the macro name is still referencing Book1 instead of the name of the workbook (Book2) that I am actually in. Having to go into each Macro-assigned shape button's settings and fixing the links (by removing the workbook reference) can be a real pain, especially if you have a lot of buttons to fix!

So how can you prevent this from happening? Well, the answer is YOU CAN'T prevent it from happening, but you CAN use VBA to fix all your macro links once you've copied over your worksheets. Simply run the following macro while the worksheet is active and it will go through all your shapes and fix any links that have references to a workbook.

Sub ShapeMacroLink_RemoveWorkbookRef()
'PURPOSE: Remove an external workbook reference from all shapes triggering macros
'Source: www.TheSpreadsheetGuru.com

Dim shp As Shape
Dim MacroLink As String
Dim SplitLink As Variant
Dim NewLink As String

'Loop through each shape in worksheet
  For Each shp In ActiveSheet.Shapes
  
    'Grab current macro link (if available)
      MacroLink = shp.OnAction
    
    'Determine if shape was linking to a macro
      If MacroLink <> "" And InStr(MacroLink, "!") <> 0 Then
        'Split Macro Link at the exclaimation mark (store in Array)
          SplitLink = Split(MacroLink, "!")
        
        'Pull text occurring after exclaimation mark
          NewLink = SplitLink(1)
        
        'Remove any straggling apostrophes from workbook name
            If Right(NewLink, 1) = "'" Then
              NewLink = Left(NewLink, Len(NewLink) - 1)
            End If
        
        'Apply New Link
          shp.OnAction = NewLink
      End If
  
  Next shp
  
End Sub

Fixing Every Worksheet In The Workbook At Once

If you are copying multiple worksheets that house buttons assigned to macro code, you can use the following VBA code to loop through all worksheet tabs in the ActiveWorkbook.

Sub ShapeMacroLinkAll_RemoveWorkbookRef()
'PURPOSE: Remove any external workbook references from all shapes triggering macros in Activeworkbook
'Source: www.TheSpreadsheetGuru.com

Dim shp As Shape
Dim sht As Worksheet
Dim MacroLink As String
Dim SplitLink As Variant
Dim NewLink As String

'Loop through each shape in each worksheet
  For Each sht In ActiveWorkbook.Worksheets
    For Each shp In sht.Shapes
    
      'Grab current macro link (if available)
        MacroLink = shp.OnAction
      
      'Determine if shape was linking to a macro
        If MacroLink <> "" And InStr(MacroLink, "!") <> 0 Then
          'Split Macro Link at the exclaimation mark (store in Array)
            SplitLink = Split(MacroLink, "!")
          
          'Pull text occurring after exclaimation mark
            NewLink = SplitLink(1)
          
          'Remove any straggling apostrophes from workbook name
            If Right(NewLink, 1) = "'" Then
              NewLink = Left(NewLink, Len(NewLink) - 1)
            End If
          
          'Apply New Link
            shp.OnAction = NewLink
        End If
    
    Next shp
  Next sht
  
End Sub

Fully Automating This Process

This post was inspired by an email I received today from someone who purchased my unlocked  Exporter Template. The Exporter Template allows you to completely automate exporting pre-determined worksheets into various file formats and even allows you to email that file through Microsoft Outlook. All with the click of a button

The problem was, this individual needed to export some VBA capabilities along with his worksheets and he was running into the issue of having to re-link all his macro buttons prior to emailing the file as an attachment.  

In order to fix this, I recommended him to add the following subroutine which accepts a workbook variable to apply the macro link fixes as part of the VBA automation process. This removes the step of having to go back an manually run a second macro to fix all your macro button links.

In the following code, I have one macro that copies a workbook and then runs (calls) a second macro to clean up all the macro button links. This is probably the solution you are most likely going to want to incorporate if you are automating your worksheet duplication.

Sub CopyWorkbook()
'PURPOSE: Copy the active workbook into a new workbook
'Source: www.TheSpreadsheetGuru.com

Dim wb As Workbook

'Make a copy of active workbook
  ActiveWorkbook.Worksheets.Copy

'Store new workbook into a variable
  Set wb = ActiveWorkbook

'Fix any macro assigned buttons
  Call FixMacroLinks(wb)

End Sub

Sub FixMacroLinks(myWorkbook As Workbook)
'PURPOSE: Localize any shape macro links (needs a target workbook to work)
'Source: www.TheSpreadsheetGuru.com

Dim shp As Shape
Dim sht As Worksheet
Dim MacroLink As String
Dim SplitLink As Variant
Dim NewLink As String

'Loop through each shape in each worksheet
  For Each sht In myWorkbook.Worksheets
    For Each shp In sht.Shapes
    
      'Grab current macro link (if available)
        MacroLink = shp.OnAction
      
      'Determine if shape was linking to a macro
        If MacroLink <> "" And InStr(MacroLink, "!") <> 0 Then
          'Split Macro Link at the exclaimation mark (store in Array)
            SplitLink = Split(MacroLink, "!")
          
          'Pull text occurring after exclaimation mark
            NewLink = SplitLink(1)
          
          'Remove any straggling apostrophes from workbook name
            If Right(NewLink, 1) = "'" Then
              NewLink = Left(NewLink, Len(NewLink) - 1)
            End If
          
          'Apply New Link
            shp.OnAction = NewLink
        End If
    
    Next shp
  Next sht
  
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 :)

How To Create Your Own User-Defined Functions With VBA

$
0
0
Create Custom Excel Functions For Formula Bar

Hey everyone! Chris here and I want to introduce you to author/blogger Allen Wyatt. Allen has been running a weekly Microsoft Office tips newsletter since 1997! I was absolutely ecstatic when he reached out with interest for writing a guest post for this blog. Allen has recently entered into the online course area of teaching and has put together a very high-quality course for learning how to write VBA macros. I asked if he would cover one of my favorite sections from his course, walking through custom function creation. Enjoy!

Understanding User-Defined Functions

Mention the word "function" to an Excel user, and immediately they'll envision common functions such as SUM or DATE or even VLOOKUP. This is understandable, as Excel makes available hundreds of functions you can use in your own formulas to massage your data.

Those with experience creating macros, however, may need additional clarification when the word "function" is used. You see, there are actually three different types of functions available to Excel users. The first is the familiar Worksheet Functions like SUM or DATE or VLOOKUP. These are built into Excel and are used extensively in worksheets.

The second type of function is what I refer to as a Procedure Function, which is a common programming structure used by those developing macros. A procedure function is used to perform some operation and then return a value to whatever programming code called that function.

The third type of function is known as a User-Defined Function (UDF). It is this third type of function that makes Excel extremely powerful as it allows you to access the power of macros directly from within your worksheets.

Think about that for just a moment: You can create a macro that can be accessed from within a worksheet, just like any other worksheet function! This means that if you create UDFs you aren't limited to only those functions provided by Excel; you can create functions that do just about anything you can imagine.

The trick to creating your own UDFs is to determine what single piece of information you want that function to return, along with what pieces of information you need to provide to it. For example, let's say you needed to routinely determine the number of uppercase "X" characters residing in a range of cells. What you need back is a count (a number) and what you need to supply is the range of cells to check.

Here's an example of a UDF you might come up with:

Function NumXs(rng As Range) As Integer

Dim iCnt As Integer
Dim c As Range
Dim sTemp As String
Dim J As Integer

iCnt = 0

For Each c In rng.Cells
  sTemp = c.Value
  
  For J = 1 To Len(sTemp)
    If Mid(sTemp, J, 1) = "X" Then iCnt = iCnt + 1
  Next J
  
Next c

NumXs = iCnt

End Function

Parts Of A User Defined Function

For those who know how to program macros, you may immediately recognize that a UDF has a structure very similar to regular VBA functions. If you aren't familiar with macros, though, this type of macro code can be a bit intimidating. If you've got this feeling, it may be helpful to take a look at each part of the macro. Let's start with the first line:

Function NumXs(rng As Range) As Integer

This line simply tells VBA (Visual Basic for Applications, which is the language used by macros in Excel) that you are defining a function, that it's name is "NumXs", that the function will work with a range of cells you want to refer to as "rng", and that the result of the function will be an Integer value (a whole number).

When working with your own UDFs, the two things you are most likely to change in this line are the function name (NumXs) and the function result type (Integer). The other elements of this line are very common and don't get changed all that often.

The next four lines in the UDF are these:

Dim iCnt As Integer
Dim c As Range
Dim sTemp As String
Dim J As Integer

These are declarations of variables that will be used in the main body of the UDF. Each line consists of the Dim keyword followed by the name of the variable, the As keyword, and the data type for the variable. Each variable has a specific purpose, determined when you actually envision what the UDF will accomplish. For instance, iCnt is a variable that will serve as a counter for the number of X characters found.

The next seven lines in the UDF do the actual work of looking at what is in each cell:

iCnt = 0

For Each c In rng.Cells
  sTemp = c.Value
  
  For J = 1 To Len(sTemp)
    If Mid(sTemp, J, 1) = "X" Then iCnt = iCnt + 1
  Next J
  
Next c

The code starts off by setting the counter (iCnt) to 0. This is followed by a special programming structure known as a For Next loop. In this instance, it means that for each cell in the range passed to the UDF, all the programming lines between "For Each" and "Next c" will be repeated. Those lines first grab the value of whatever is stored in each cell and store that value in the sTemp variable. Then, another For Next loop is used which examines each character in the sTemp variable. If that character is "X", then the counter (iCnt) is incremented.

The next line of the UDF is very important:

NumXs = iCnt

This makes the NumXs variable equal to the value in the counter (iCnt). Note that the NumXs variable has the same name as the function itself, as stated in the first line of the UDF. Assigning the value to NumXs in this way informs VBA of the value that should be returned from the UDF.

That leaves just one last line in the UDF:

End Function

This line tells VBA that the end of the UDF has been reached. (Everything between the first line—the one that starts with "Function"—and this line is considered part of the UDF.)

Using A User-Defined Function In Your Spreadsheet

So how do you use the UDF in your worksheet? Just the same as you would any other worksheet function. For instance, if you wanted to know the number of "X" characters in the range A2:A15, you could use the following in a cell:

=NumXs(A2:A15)

The function returns the number of uppercase "X" characters in the range A2:A15. The result is stuffed into the cell just as soon as you press Enter after typing the formula.

Below is a look of how you might use this function in a spreadsheet environment:

Create Custom Excel Functions For Formula Bar

Obviously the example provided in this article is rather simplistic—most people never need to know how many uppercase "X" characters are in a range of cells. What it should demonstrate, however, is that through the use of UDFs you can expand how you process your data in a worksheet. They are very powerful and not that hard to create, so give it a try with your processing needs.

If you are baffled by "all things macro," however, you would do well to check out an online course that could help improve your skills. What you've learned above is just one part of my Excel Macros for Beginners course, which can help you make sense of macros and even create your own. And, as the title promises, it is a course designed for beginners just like you.

Want to know more? Check out UsingOffice.com


Allen Wyatt Excel Author

Allen Wyatt is the author and publisher of the ExcelTips newsletter, published at no cost to recipients every week for the last 18 years. You can find out more about him at AllenWyatt.com. His course, Excel Macros for Beginners, is available at UsingOffice.com.


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 Excel Keyboard Shortcuts For Editing Columns & Rows

$
0
0
Top Excel Spreadsheet Shortcuts For Columns And Rows

Hey everyone! Chris here and I want to introduce you to instructor/blogger Rishabh Pugalia from YodaLearning.com. He has graciously offered to stop by the blog and share with us some of the knowledge he currently teaches to the students in his online courses. Take it away Rishabh!

Why Use Shortcuts Anyways?

Excel is so versatile that it can be used by people from a variety of industries including students, teachers, businessmen, etc... Hence, in order to cater to such a huge and diversified audience, Microsoft had to incorporate a huge number of features in Excel. As a result, Excel has a steeper training curve compared to other spreadsheet software currently available.

While most people consider this to be a disadvantage, that really isn’t true. It can definitely be said that for a beginner, the vast number of features in Excel seem overwhelming, but if you know a few shortcuts in Excel, the tasks can become much more simple. By using the correct shortcuts, you can also save a lot of precious time, which can be utilized for other productive work. Check these 6 shortcuts in Microsoft Excel which can be used to make manipulating columns and rows a breeze!

Insert A New Column

Inserting a new column in Excel is probably one of the most frequently used tasks. Normally, the user right-clicks on a particular column and then selections the Insert option to add a new column. Notice that you have to use the mouse for this task. If you are using the keyboard, then switching to the mouse can be time-consuming.

That is why Microsoft has added an easy shortcut to insert a new column without ever using the mouse. Just press Alt + I + C ("I" for insert, "C" for column) and you will find that a new column has been added to the left of the currently selected column.

Insert A New Row

Inserting a new row is also often used. Normally, if you don’t know any Excel keyboard shortcuts, you will add a new row by right-clicking on a row and selecting Insert to add a new row. This will create a new row above the selected row. Although you might think this is pretty straightforward and won’t take much time, for people who are very productive this can be quite annoying. If you are using the keyboard and you have to switch to the mouse every now and then, it is very inconvenient for the end user.

Fortunately, there is an easy shortcut. Just press Alt + I + R  ("I" for insert, "R" for row) to create a new row.

Excel Shortcut Insert Rows Columns

Selecting An Entire Column

Insertion is definitely one of the more frequently used tasks in Excel, but once the columns have been set, modifying the data requires selection. There are multiple ways via which you can choose columns in Excel. The easiest and the most straightforward way is to choose the starting cell of that column with your mouse and continue holding the left mouse button while traversing down the column. That way you can select the entire column or even a part of it if required.

You can also do a similar task using the keyboard. Just as we select text in Word or PowerPoint, move the cursor to the top cell, and while holding shift, press the down arrow button on the keyboard to select the specific rows you want.

However, both of these are time-consuming. When you are certain that you want to select the whole column, just press Ctrl + Spacebar which will select the entire column(s) based on the cell range that is currently selected.

Selecting An Entire Row

Now that you know how to select entire columns, you must be wondering how do I so the same thing for rows? Just like columns, rows too can be selected by left-clicking the top cell and moving the cursor right with the mouse or via holding down the shift button on the keyboard while the cursor is in the first cell of the row, and then pressing the right arrow button.

However, a better solution is to press Shift + Spacebar to select the entire row.

Microsoft Excel Spreadsheet Select Entire Row Column Keyboard Shortcut

Inserting Rows Or Columns

Remembering separate shortcuts for inserting rows and columns might be a bit difficult for some people (our brain can only store so many shortcuts, right?). That is why another shortcut combination is present in Excel: Ctrl + Shift + Plus Sign. This combination brings up the Insert dialog box and asks you if you want to shift cells or insert rows or columns.

Deleting Rows Or Columns

Deletion is just as important as insertion. To display the Delete Dialog Box, you can us the shortcut combination Ctrl + Minus Sign. Just like the previous shortcut, it first asks you whether you want to delete the entire row or column or shift cells. Click on the option needed and it will perform the task accordingly. 

Excel Spreadsheet Shortcut Delete Insert Dialog Boxes

See These Shortcuts In Action!

These 6 shortcuts should prove to be immensely beneficial in your daily work and are guaranteed to give a boost to your productivity. See these shortcuts in action in my following video.


Yoda Learning Excel Instructor Rishabh Pugalia

Rishabh Pugalia is the Co-Funder of Yoda Learning. He is a Chartered Accountant and has experience working with KPMG and J.P. Morgan. He is Microsoft Office Expert and has created the Excel Ninja and PowerPoint Ninja online courses at YodaLearning. He’s also a die-hard fan of Counter Strike! 


Preventing Users From Printing Your Excel Workbook Tabs With VBA

$
0
0
Disable Printing Capabilities In Excel Spreadsheet File

Sometimes when you have models that are dealing with sensitive information, you want to take extra steps to prevent that data from getting passed around. In this article, you will be walked through different scenarios where you can prevent anyone from using the Print features to makes printouts of your Excel tabs.

A Couple Caveats To Disabling The Printing

First, I'll state the obvious. While this solution might deter people from printing your worksheets, it will definitely not prevent people from taking screenshots and printing those. This solution is really just going to make it a hassle to print out your data and hopeful serves as a reminder to your audience that they shouldn't be printing out the data stored in the workbook.

Secondly, the VBA you will be using is going to be triggered by the "Printing" action and therefore, it will only work if VBA Events are enabled in Excel. VBA Events are enabled by default and can only be turned off when macros are disabled or when your use VBA code to turn VBA Events off.

Most Excel users are not going to be advanced enough to know to turn off VBA Events, but it might be a good idea to create a physical button in your workbook that the user must click in order to use the file.  A common practice would be to hide all the worksheets with the xlVeryHidden property and leave a single worksheet with a button that is assigned to a macro. Once clicked, the button could execute code to unhide all the worksheets and ensure that VBA Events are active. This code could look something like this:

Sub FileStartup()

Dim sht As Worksheet

'Optimize Code
  Application.ScreenUpdating = True

'Loop Through Each Worksheet And Unhide
  For Each sht In ThisWorkbook.Worksheets
    sht.Visible = xlVisible
  Next sht

'Ensure VBA Events Are Turned On
  Application.EnableEvents = True

End Sub

Where To Store These Macros

VBA ThisWorkbook Object Module

Unlike normal VBA macros and functions, event-triggered macros need to be stored in a Worksheet Object Module or in the case of this article, the Workbook Object Module. To get to this module, you will need to double-click on the ThisWorkbook Object name within the Microsoft Excel Objects folder in your Project Window (within the Visual Basic Editor). After you double-click, you will see a white sheet appear and you can proceed to store your event-triggered macros within the object. For further information on this subject, you can read my article discussing how to trigger your macros automatically with event handlers.

VBA Macro To Prevent Anything From Being Printed

I first going to start out with a VBA snippet that will disable printing for the entire workbook. It is going to be "triggered" on the BeforePrint event....which means the code will run before any printing can be had.

This code is actually quite simple in that it literally just changes the figurative Cancel button on (ie True) and then notifies the user that they cannot print any worksheet with this Excel file.

Private Sub Workbook_BeforePrint(Cancel As Boolean)
'PURPOSE: Prevent user from printing this workbook
'NOTES: This Code Must Reside in the ThisWorkbook Object
'SOURCE: www.TheSpreadsheetGuru.com/the-code-vault

'Cancel the Print Request
  Cancel = True

'Notify User They Cannot Print this workbook
  MsgBox "You do not have permission to print this file", vbOKOnly, "Cannot Print"
  
End Sub

Prevent Printing Of A Specific Worksheet

Now let's take the previous macro code one step further and assume you only really care about one worksheet being printed. Provide a name of the worksheet you want to disable and the code will go through and check to see if that particular worksheet is currently selected to print.

If someone wanted to be cute, they could just change the name of the worksheet and bypass this macro's functionality. To strengthen this macro even more, I would recommend referencing the code name instead of the text name as most people don't know how to change a worksheet's code name.

Private Sub Workbook_BeforePrint(Cancel As Boolean)
'PURPOSE: Prevent user from printing A Specific Worksheet
'NOTES: This Code Must Reside in the ThisWorkbook Object
'SOURCE: www.TheSpreadsheetGuru.com/the-code-vault

Dim WorksheetName As String
Dim sht As Worksheet

WorksheetName = "Sheet1"

For Each sht In ThisWorkbook.Windows(1).SelectedSheets
  
  If sht.Name = WorksheetName Then
    'Cancel the Print Request
      Cancel = True
      Exit For
  End If
Next sht

'Notify User They Cannot Print this workbook
  MsgBox "You do not have permission to print the [" _
   & WorksheetName & "] worksheet", vbOKOnly, "Cannot Print"
  
End Sub

Disable Printing For Multiple Worksheets

Below is another variation that allows you to prevent the printing of multiple specifc worksheets within your Excel file. Again, you can strengthen this by using worksheet code name references instead of the worksheet name.

Private Sub Workbook_BeforePrint(Cancel As Boolean)
'PURPOSE: Prevent user from printing Specific Worksheets
'NOTES: This Code Must Reside in the ThisWorkbook Object
'SOURCE: www.TheSpreadsheetGuru.com/the-code-vault

Dim DoNotPrintList As String
Dim DisablePrint As Variant
Dim sht As Worksheet

'Store Names of worksheets that can't be printed
  DisablePrint = Array("Sheet1", "Sheet3", "Sheet5")

'Create a list of all the sheets not allowed to be printed
  For x = LBound(DisablePrint) To UBound(DisablePrint)
    DoNotPrintList = DoNotPrintList & DisablePrint(x) & ";"
  Next x

'Loop through each worksheet that is currently selected
  For Each sht In ThisWorkbook.Windows(1).SelectedSheets
    'Cancel the Print Request if Sheet Name Should not be printed
      If DoNotPrintList Like "*" & sht.Name & ";*" Then
        Cancel = True
        Exit For
      End If
  Next sht

'Notify User They Cannot Print this worksheet
  MsgBox "You do not have permission to print the [" _
   & sht.Name & "] worksheet", vbOKOnly, "Cannot Print"
  
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  :)


Combining Text With The CONCAT and TEXTJOIN Excel Functions

$
0
0
Combining Text With Concat and TextJoin Excel Spreadsheet Functions

Hey everyone! Chris here and I want to introduce you to a new Excel blog called Spreadsheeto. Bloggers Mikkel and Kasper hail from the Denmark where they have been successful in providing online training to the Danish community. With the birth of their new website, Spreadsheeto.com provides English-based training aimed at teaching the entire world! They have offered up their expertise today to teach us a couple brand new formula functions that were released in the most recent update of Excel 2016. Enjoy!

The Art Of Combining Text

There are a variety of reasons why you might want to combine various cell values into a single value. You might be trying to create a unique ID to perform a lookup or simply wanting to combine location information such as a city with a country. The Microsoft Excel developers have recognized the importance of joining our data inside of Excel and have finally added two more extremely useful functions that we can incorporate into our arsenal of text manipulating skills. In this article, you will learn the basics of combining text with these brand new functions and hopefully you gain some insight into how you can use them inside your spreadsheet work on a regular basis.

AND DON'T WORRY...If you are currently using a version of Excel that was released prior to Excel 2016, in the last section of this very article you will learn how you can get your hands on these functions in any version of Excel!

The New Concatenating Function, CONCAT

CONCAT() is an exciting new function available in the latest versions of Excel (Excel 2016, Excel Mobile, and Excel Online). While its predecessor CONCATENATE() is still available in newer versions of the application, it is recommended that you use CONCAT() instead. The CONCAT() function accomplishes everything CONCATENATE() has in the past but now offers some new additional flexibility. More about that in a moment.

First, let’s discuss the basics of what CONCATENATE() actually does. If you have ever had data in multiple cells that you needed to join, CONCATENATE() has most likely been your answer.  However, it is not the only method by which you can do this in Excel. Take a look at the example below. There are two cells with data associated with a person's name.

Concatenation Excel Spreadsheet Functions

We could use the CONCATENATE() function to derive the full name, but to be honest, it’s just as simple to use the ampersand sign (ie &) to join the contents of these cells.

Concatenation Excel Spreadsheet Functions

Notice that it is necessary to place a space value (ie " ") between the contents of Cell A2 and Cell B2. This is in order to obtain the result of a joined string with a space between the first and last name. Now let’s see the same outcome but now by using the CONCATENATE() function.

Concatenation Excel Spreadsheet Functions

Clearly, from these examples you can see that the same results can be accomplished by using different methods. In fact, you might argue that the use of CONCATENATE() is the more complicated of the two methods shown here due to the length of the characters you need to write.                

The syntax of the CONCATENATE() function is =CONCATENATE (text1, [text2], …). At its most basic, the function will allow you to join the contents of multiple cells like we saw before by placing a comma between each string of text whether it is a cell reference or literal text.

Before we move on to the exciting new capabilities of CONCAT(), let’s take a quick look at how you can expand the joining of multiple cell contents in another practical sense by placing literal text in the string to be joined. Consider the following data.

Concat Function Example In Excel Spreadsheet

Our objective here is to create a formal sentence that analyzes the sales results for the month. In this case, we will not only insert the contents of the cells in our CONCATENATE() formula, but also the literal text creating the sentence. The result we aim to get should read as follows:

We saw 24% growth with sales reaching $105M.

In the explanation below, notice the insertion spaces added to the inserted literal text (ie "We saw "). Whatever you insert in the function between double quotes will be output to your resulting string.  

Pro Tip: If you need to add quotes into your sentence, you can use the formula =CHAR(34) to create a double quote character. For example = CHAR(34) & "Sales" & CHAR(34) would output a result of "Sales".

Concat Function Example In Excel Spreadsheet

Recall from our first example that the CONCATENATE() formula joins the literal contents of the cells we enter into the formula. Therefore, be aware that if there are no spaces between entries, you will need to add them to your formula to compensate if you want spaces in between.

At this point you may be thinking "this is all great, but I thought we were going to look at the CONCAT() function". Good point! So let’s move on.

Introducing The Brand New CONCAT Function

The main limitation of the CONCATENATE() function that CONCAT() has now addressed is we as users can now select a range of cells to join while previously we were limited to referencing a list of single cells. Let’s take a look.

Concat Formula In Excel 2016 Spreadsheet

This is a very powerful new capability, especially if you have a lot of columns of data to join. Further, notice in the example above that on row 3 there is no data in the “Middle” field (column B) yet CONCAT() completely skipped it and joined the next cell into the range.

This specific example using names as the string data to join does raise an interesting question: what do we do if we need spaces (or other characters) in between the data we are joining? While CONCAT() does not provide us with a direct method for this, there is now another function that can assist us with this.

Adding Space Delimiters With The TEXTJOIN Function

Referring to the previous example, we can use a different function called TEXTJOIN() to incorporate space delimiters (characters that separates a list of words) into our full names. Let's first cover the 3 inputs of TEXTJOIN():

  1. Delimiter - This is a designated character or string of characters that will be inserted in between each "Text" or "Cell" input provided.
  2. Ignore_Empty - This is a TRUE or FALSE input that asks if you want to ignore blank values. If FALSE, you run the risk of have two delimiter characters next to each other (for example, a result of "Apple,Orange,Banana" could end up being "Apple, Orange,,Banana")
  3. Text - the text item(s) to be joined. This can be a text string, or array of strings (such as a range of cells).These are the same exact inputs you would use with the CONCATENATE() or CONCAT() functions.

Now that you have an idea of what inputs go into using the TEXTJOIN() function. Let's go back to our name example and try to combine the First, Middle, and Last names so that they read intuitively with spaces.

Textjoin Function Example In Excel Spreadsheet

You can see that we delimited each cell's text value with a space and ignored any blank values (ie Cell B3). Now, what would the results look like if we changed the Ignore_Empty input to have a FALSE value?

Let's look at another example where we delimit with commas so you can better see the impact.

Textjoin Formula Example In Excel Spreadsheet

As highlighted in the above image, the blank value in cell B3 gave a result of back-to-back delimiters (,,). Depending on your situation this may be what you want, but in most cases you will  likely want to keep the Ignore_Empty input set to TRUE.

VBA User Defined Functions For Excel Versions Prior To 2016

If you do not have Excel 2016, there is still a way you can take advantage of these functions. Below is the VBA coding that will mimic the functionality of CONCAT and TEXTJOIN. You can embed this VBA macro code inside your spreadsheets and automatically be able to call them from your formula bar just like a normal built-in spreadsheet function.

To add these functions, use the keyboard shortcut ALT + F11 to open up the Visual Basic Editor. Once inside the editor, you will want to

  1. Right-click on the name of the file you are currently using
  2. Go to Insert
  3. Click Module
  4. In the white space, paste the code 
  5. Exit out of the Visual Basic Editor window
  6. Save your file

Then start typing in the function in your formula bar and you should see it appear inside the formula suggestion box! If you need additional help with this process you can read through Lesson Two of TheSpreadsheetGuru's Crash Course on VBA.

The CONCAT Function

Public Function CONCAT(ParamArray Text1() As Variant) As String
'PURPOSE: Replicates The Excel 2016 Function CONCAT
'SOURCE: www.TheSpreadsheetGuru.com

Dim RangeArea As Variant
Dim Cell As Range

'Loop Through Each Cell in Given Input
  For Each RangeArea In Text1
    If TypeName(RangeArea) = "Range" Then
      For Each Cell In RangeArea
        If Len(Cell.Value) <> 0 Then
          CONCAT = CONCAT & Cell.Value
        End If
      Next Cell
    Else
      'Text String was Entered
        CONCAT = CONCAT & RangeArea
    End If
  Next RangeArea

End Function

The TEXTJOIN Function

Public Function TEXTJOIN(Delimiter As String, Ignore_Empty As Boolean, ParamArray Text1() As Variant) As String
'PURPOSE: Replicates The Excel 2016 Function CONCAT
'SOURCE: www.TheSpreadsheetGuru.com

Dim RangeArea As Variant
Dim Cell As Range

'Loop Through Each Cell in Given Input
  For Each RangeArea In Text1
    If TypeName(RangeArea) = "Range" Then
      For Each Cell In RangeArea
        If Len(Cell.Value) <> 0 Or Ignore_Empty = False Then
          TEXTJOIN = TEXTJOIN & Delimiter & Cell.Value
        End If
      Next Cell
    Else
      'Text String was Entered
        If Len(RangeArea) <> 0 Or Ignore_Empty = False Then
          TEXTJOIN = TEXTJOIN & Delimiter & RangeArea
        End If
    End If
  Next RangeArea

TEXTJOIN = Mid(TEXTJOIN, Len(Delimiter) + 1)

End Function

And there you have it, 2 new functions for you to use!

You now know the basics of two functions that can be quite powerful while combining your data. CONCAT() takes the capabilities previously available with CONCATENATE() to an entirely new level of functionality. And TEXTJOIN() builds on CONCAT() to provide even more versatility.

Got any questions or thoughts? Leave a comment below!


kasper & mikkel of Spreadsheeto.com

Mikkel and Kasper are the creators of Spreadsheeto who wrote this very article. Love Excel? Be sure to visit Spreadsheeto's blog


Allow User-Specific Login Credentials To Be Pulled With Excel VBA

$
0
0
Multiple User Login Private Credential Information

There are a ton of great data programs out there that integrate very nicely with Excel. The problem I see handled poorly over and over again is that analysts will store their login credentials directly inside their automated VBA code or even worse, the spreadsheet itself!

In this tutorial, I want to show you an easy way to bring a user's unique username and password into a VBA macro without exposing this sensitive information within the VBA project or the Excel spreadsheet file itself.

A Real World Scenario

Let's imagine a real world scenario that happens all the time in the corporate world.

John wants to create an automated analysis spreadsheet that his 2 co-workers can also use to perform analysis for their company. This spreadsheet will be stored on the company's shared drive so anyone can access the file whenever needed.

John's initial thought is to gather his and his co-worker's username and password and hard code this information into his macro so none of them have to keep logging into the database system when they want to query information.

John uses Array variables to store the credentials into lists that correspond with their individual computer's ID number. The VBA code looked something like this:

Sub DatabaseLogin()
'PURPOSE: Log into Company's Database via Excel VBA

Dim ID_List As Variant
Dim Username_List As Variant
Dim Passoword_List As Variant
Dim Username As String
Dim Password As String
Dim x As Integer

'Team Members' Credentials
  ID_List = Array("x302918", "x294832", "x392490")
  Username_List = Array("JohnSmith", "JasonBorne", "FelixHarp")
  Passoword_List = Array("ILuvMommy5", "HulkMan123", "IneedSleep665")

'Test for Team Memember's ID
  For x = LBound(ID_List) To UBound(ID_List)
    If Environ("USERNAME") = ID_List(x) Then
      Username = Username_List(x)
      Password = Username_List(x)
      Exit For
    End If
  Next x

'Unidentified User, must manually login
  If Username = "" Then
    Username = Application.InputBox("Enter Your Username")
    Password = Application.InputBox("Enter Your Password")
  End If

'Log Into Database
  AccessDatabase Username, Password, "CustomerDatabase"
  
End Sub

Besides the humiliation of sharing your dorky passwords you created when you were in middle school, hopefully, it is obvious why this above scenario would not be preferred by any means!

A Better Way To Pass-Thru Credentials With VBA

The way I prefer to address this issue is to have each individual store their credentials on their own secure computer. To do this, they can simply create a text file in NotePad in a CSV (comma separated) format. Within the text file, have each user type their username and password (separated with a comma) as shown below.

Multiple User Login Private Credential Information Text File

You need all your users to save the file with the same file name and in the same location on their computers. In this example, the file name will be "Credentials.txt" and the file location will be on the computer's Desktop (you could easily use the Documents folder or a custom-named folder within the C\ drive).

VBA To Pull Log In Information From A Text File

The foundation of this VBA code will come from an article I wrote entitled: The VBA Guide To Interacting With Text (.Txt) Files. Within this post, there is code that shows you how to extract text from within a text file with VBA coding. You will need to use this process in order to pull the credential string of text out of the text file created in the previous section. Below is the completed solution and I will walk you through each part of the code in the following section.

Sub DatabaseLogin()
'PURPOSE: Log into Company's Database via Excel VBA & Desktop Text File

Dim Username As String
Dim Password As String
Dim TextFile As Integer
Dim FilePath As String
Dim Credentials As Variant

'File Path of Text File
  On Error Resume Next
    FilePath = Environ("USERPROFILE") & "\Desktop\Credentials.txt"
  On Error GoTo 0
  
'Determine Login creditials (manual or automatic from desktop file)
  If FilePath = "" Then
    Username = Application.InputBox("Enter In Your Username")
    Password = Application.InputBox("Enter In Your Password")
  
  Else
    'Determine the next file number available for use by the Open function
      TextFile = FreeFile
    
    'Open the text file
      Open FilePath For Input As TextFile
    
    'Store file content inside array variable and determine login info
      Credentials = Split(Input(LOF(TextFile), TextFile), ",")
        Username = Credentials(0)
        Password = Credentials(1)
    
    'Close Text File
      Close TextFile
  
  End If

'Log Into Database
  AccessDatabase Username, Password, "CustomerDatabase"
  
End Sub

Explaining How This VBA Macro Works

What this VBA code first does is look for a specified text file within the desktop. You can pull the unique default drive path by using the Environ function. For my computer, Environ("USERPROFILE") equates to C:\Users\Chris. You can then append the rest of the folder path and the file name to the Environ function to create a complete path unique to the currently running computer. An error handling statement is wrapped around this line of code in case the user does not have the file saved to the specific location you designate (in which case they will need to manually enter in their login information).

'File Path of Text File
  On Error Resume Next
    FilePath = Environ("USERPROFILE") & "\Desktop\Credentials.txt"
  On Error GoTo 0

Next there is an IF statement to determine if the login credential file was found on the computer. If manual inputs are needed, the user will be prompted by an input box asking for the username and then the password.

'Determine Login creditials (manual or automatic from desktop file)
  If FilePath = "" Then
    Username = Application.InputBox("Enter In Your Username")
    Password = Application.InputBox("Enter In Your Password")
  Else
    'Credentials were able to be pulled from the text file
  End If

If the VBA code was able to find the text file within the designated location, it will then open up the file and extract the text stored inside. Next, a Split function is used to separated the string of text by the comma symbol. All the individual pieces left over from the split are then stored inside an array variable (think list) beginning in position zero. Here is my attempt at showing you visually what is going on:

VBA Split Function Example

And here is this concept coded in VBA:

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

'Open the text file
  Open FilePath For Input As TextFile

'Store file content inside array variable and determine login info
  Credentials = Split(Input(LOF(TextFile), TextFile), ",")
    Username = Credentials(0)
    Password = Credentials(1)

'Close Text File
  Close TextFile
  

To complete the login process, you will need to know how to specifically log into your company's database through VBA. This will typically be located in a database's API documentation. Below are some links to examples of popular business software documentations showing how you can connect into Excel with VBA.

Feel free to help me build this list out even more by leaving a link in the comments section near the end of this article!

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 :)

Retain Font Formats After Changing An Excel Shape's Formula

$
0
0
Prevent Font Formats Changing While Modifying Excel Shape Formulas

This is a frustration I seem to always face while creating dashboards or graphics for Excel reports. I create a super cool callout graphic to bring attention to an important figure in my data. I have this graphic perfectly formatted and proceed to copy it a couple of times to link some more important figures to these callouts. In my example below, I started with the "Ohio" and linked it to some cells to make it dynamic. I then proceeded to copy it twice to create a callout forthe states of Iowa and Maine.

Link Formula to Excel Shape or Textbox

The problem arises when you go and try to adjust the shape or textbox formulas to a link to a different cell address. For some reason, Excel wants to reset the the font format after a formula change. Then the pain begins...you have to go back and reformat each of the graphics (either manually or with the Format Painter button). What a pain in the butt!

Problems Modifying Excel Shape Formulas

A Solution To Prevent This

After running into this issue for quite some time and failing to find any solution on the internet, I did what any VBA coder would do....create a solution from scratch. With the macro solution I drew up, you can select the shape you want to adjust and modify cell address link while maintaining the text formats.

The Magic Trick: The VBA code stores the font formats before the formula gets changed and then re-applies the formats to the shape.

VBA Macro Solution Modifying Excel Shape Formulas

The VBA Macro Solution

Below is the code I came up with and use on a regular basis while creating graphics and callouts that need to display data. All you need to do is copy this code into your Personal Macro workbook and then you can access it whenever you need it (I have this macro placed in my Quick Access Toolbar or QAT also).

Sub LinkShape_RetainFormat()
'PURPOSE: Prevent The Resetting Of Font Format When Changing An Excel Shape's Formula
'SOURCE: www.TheSpreadsheetGuru.com

Dim shp As Shape
Dim LinkCell As Range
Dim FontBold As Boolean
Dim FontItalic As Boolean
Dim FontColor As Long
Dim FontSize As Long
Dim FontUnderline As Long
Dim FontName As String
Dim myAnswer As Variant

'Determine If Selection Is A Shape
  On Error GoTo InvalidSelection
    Set shp = ActiveSheet.Shapes(Selection.Name)
  On Error GoTo 0

'Store Current Font Settings
  With shp.TextFrame2.TextRange.Font
    FontBold = .Bold
    FontColor = .Fill.ForeColor
    FontSize = .Size
    FontItalic = .Italic
    FontUnderline = .UnderlineColor
    FontName = .Name
  End With

'Ask User For New Cell To Link To
  On Error GoTo UserCancelled
    Set LinkCell = Application.InputBox("Select a single cell to link to", Type:=8)
  On Error GoTo 0
  
'Change Shape's Cell Link
  Selection.Formula = "=" & LinkCell.Cells(1, 1).Address

'Restore Original Font Settings
  With shp.TextFrame2.TextRange.Font
    .Bold = FontBold
    .Fill.ForeColor.RGB = FontColor
    .Size = FontSize
    .Italic = FontItalic
    .UnderlineColor = FontUnderline
    .Name = FontName
  End With

'Scroll Back to Selected Shape
  myAnswer = MsgBox("Scroll back to graphic location?", vbYesNo)
  
  If myAnswer = vbYes Then
    ActiveWindow.ScrollColumn = Selection.TopLeftCell.Column
    ActiveWindow.ScrollRow = Selection.TopLeftCell.Row
  End If
  
Exit Sub

'ERROR HANDLERS
InvalidSelection:
  MsgBox "Please select a shape object before running this code"
  Exit Sub

UserCancelled:
  Exit Sub

End Sub

[Optional] Auto-Populate Current Linked Cell

Below is the same macro as above but with one modification that I found to be useful. It auto-populates the input box with the current formula address. This can be useful if you data is located far away from where your graphic resides. This is because the input box will automatically navigate you to where the cell location is visually. Try it out!

Sub LinkShape_RetainFormat2()
'PURPOSE: Prevent The Resetting Of Font Format When Changing An Excel Shape's Formula
'SOURCE: www.TheSpreadsheetGuru.com

Dim shp As Shape
Dim LinkCell As Range
Dim FontBold As Boolean
Dim FontItalic As Boolean
Dim FontColor As Long
Dim FontSize As Long
Dim FontUnderline As Long
Dim FontName As String
Dim myAnswer As Variant

'Determine If Selection Is A Shape
  On Error GoTo InvalidSelection
    Set shp = ActiveSheet.Shapes(Selection.Name)
  On Error GoTo 0

'Store Current Font Settings
  With shp.TextFrame2.TextRange.Font
    FontBold = .Bold
    FontColor = .Fill.ForeColor
    FontSize = .Size
    FontItalic = .Italic
    FontUnderline = .UnderlineColor
    FontName = .Name
  End With

'Ask User For New Cell To Link To (Default To Current Formula)
  On Error GoTo UserCancelled
    Set LinkCell = Application.InputBox("Select a single cell to link to", _
     Type:=8, Default:=Selection.Formula)
  On Error GoTo 0

'Change Shape's Cell Link
  Selection.Formula = "=" & LinkCell.Cells(1, 1).Address

'Restore Original Font Settings
  With shp.TextFrame2.TextRange.Font
    .Bold = FontBold
    .Fill.ForeColor.RGB = FontColor
    .Size = FontSize
    .Italic = FontItalic
    .UnderlineColor = FontUnderline
    .Name = FontName
  End With

'Scroll Back to Selected Shape
  myAnswer = MsgBox("Scroll back to graphic location?", vbYesNo)
  
  If myAnswer = vbYes Then
    ActiveWindow.ScrollColumn = Selection.TopLeftCell.Column
    ActiveWindow.ScrollRow = Selection.TopLeftCell.Row
  End If

Exit Sub

'ERROR HANDLERS
InvalidSelection:
  MsgBox "Please select a shape object before running this code"
  Exit Sub

UserCancelled:
  Exit Sub

End Sub

Download An Example File

If you need a little head start or are not comfortable with VBA quite yet, I have put together a great little example Excel file with some of the examples covered in this article.

As always, in order to download this or any example file from this website, you will need to be a subscriber of my free tips 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 :)

How To Add A Center Across Selection Button To Excel's Home Ribbon Tab

$
0
0
Excel Center Across Selection Ribbon Button

Why Center Across?

I am a huge advocate for using the Excel functionality of Center Across Selection instead of Merge & Center. The main reason is it forgoes issues with copy/pasting cells that are merged. A few months ago I made a proposal on the Excel UserVoice site to squeeze in a button on the Home Tab that would provide the Center Across Selection functionality (you can read/upvote that request here).

As my request hasn't seemed to have gained much traction, I came up with this crazy idea....why don't I just do it myself! So, this weekend I spent a few hours figuring out how I could create an add-in that would hide the Alignment group on the Home tab and then re-create the Alignment group with an added Center Across button. With this little Excel Add-in you can make your Ribbon transform as follows:

Excel Center Across Selection Ribbon Button Range Alignment Group

The VBA Used For The Center Across Macro

Since macros cannot be undone, I created a reversible macro that toggles back and forth between centering across and a normal cell alignment format. Here is the VBA code I used that will get executed when you click the Center Across button

Sub CenterAcrossSelection()
'PURPOSE: Center text across selection
'SOURCE: www.TheSpreadsheetGuru.com

On Error GoTo Select_Cell:
  With Selection
    If .HorizontalAlignment = xlCenterAcrossSelection Then
      .HorizontalAlignment = xlGeneral
    Else
      .HorizontalAlignment = xlCenterAcrossSelection
    End If
  End With
On Error GoTo 0

Exit Sub

'ERROR HANDLERS
Select_Cell:
  MsgBox "Select a cell range in order to use this button."
  Exit Sub
  
End Sub

Free Download For This Excel Add-in

As mentioned above, I ended up creating a very lightweight Excel add-in that will slightly modify your Home tab in the Excel Ribbon to include a Center Across button. This add-in file is only compatible with Excel 2010 or later. If you need any help installing this add-in file, you can read my "How To" article that explains how to install an add-in file in Excel.

As always, in order to download this or any example file from this website, you will need to be a subscriber of my free tips 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

 

What Do You Think? Leave A Comment!

Was this a good idea or a complete waste of a rainy Saturday afternoon? Let me know your thoughts in the comments section below as I'm curious if anyone else out there was wanting this sort of functionality in their Home tab.


THANK YOU: I'd like to give a special thank you to Raymond T. who helped me figure out some of the XML coding for the Ribbon interface via LinkedIn for this little project.


How To Find And Remove Duplicate Excel Cell Data

$
0
0

Double Trouble

I think we have all had our fair share of experiences getting weird outcomes because of duplicate data within our cell ranges. They can easily cause your VLOOKUPs to pull unexpected values or give your subtotals problematic outcomes. Don't you fret though because there are a bunch of ways you can check and even remove duplicate rows of data within your Excel spreadsheets. Enjoy.

How To Find Duplicate Data In Your Spreadsheet

Method 1: Using A Formula

With this method, I am using a COUNTIF function to determine if there are 2 or more instances of a cell value. If multiple instances are found, then those rows are flagged with the phrase "Dup" (short for "duplicate"), but you can make your flag be any word that you wish.

For a VBA-base solution to quickly flagging duplicates on your spreadsheets, Dan Wagner put together a great article and video on his blog entitled How to Count and Label Duplicate Values Without COUNTIF or Range.Find.

Method 2: Using Conditional Formatting

Did you know you can use a conditional formatting preset to flag duplicates? I didn't for the longest time and still remember the disbelief that this simple option had been available to me the whole time! All you need to do is highlight your cell data and navigate to

Home Ribbon Tab > Conditional Formatting > Highlight Cells Rules > Duplicate Values....

From there, you can simply hit the OK button when the dialog box pops up and any cells that are duplicates will be highlighted with a light red cell fill color. Have thousands of rows that you don't want manually scroll through to check for the red fill? Well you can easily apply a filter to your data and see if you can filter on the red cell fill color.

This is a great method that is very fast to implement on data to see if there are any duplicate instances. I make a habit of using this process to check my ID columns that VLOOKUP formulas are pointed to, so I am certain I have unique values throughout the column.

Method 3: Using VBA Macro Coding

This wouldn't be a true Spreadsheet Guru article without a solution for all you VBA automators! The following is a neat little macro I whipped up that will determine if you have any duplicate values within your selected cell range.

After running the VBA macro code, you will get a message box that tells you how many duplicate cells were found and ask if you want to highlight them yellow. This would be a great addition to your Personal Macro Workbook (it's definitely in mine!).

Sub SearchForDuplicates()
'PURPOSE: Determine if there are duplicate values within the selected cell range
'SOURCE: www.TheSpreadsheetGuru.com

Dim rng As Range
Dim rngFind As Range
Dim cell As Range
Dim DupAddresses As String
Dim SearchList As String
Dim Delimiter As String

'Setup Variables
  Set rng = Selection
  Delimiter = "-;;-"

'Loop through each cell in selection
For Each cell In rng.Cells
  'Does cell have value?
    If cell.Value <> "" Then
      'Has value been searched for yet?
        If InStr(1, SearchList, cell.Value & Delimiter) = 0 Then
          SearchList = SearchList & cell.Value & Delimiter
          
          Set rngFind = rng.Find(what:=cell.Value, LookIn:=xlValues, _
            lookat:=xlWhole, searchdirection:=xlNext)
        
          If Not rngFind Is Nothing Then
            'Record first instance found
              FirstAddress = rngFind.Address
              
            'Find any next instances of value
              Do
                Set rngFind = rng.FindNext(rngFind)
                If rngFind.Address = FirstAddress Then Exit Do
                DupAddresses = DupAddresses & rngFind.Address & ","
              Loop
              
          End If
        End If
    End If
Next cell

'Report Results
  If DupAddresses <> "" Then
    Set rng = Range(Left(DupAddresses, Len(DupAddresses) - 1))
    UserAnswer = MsgBox(rng.Count & " duplicate values were found," _
      & " would you like them to be highlighted in yellow?", vbYesNo)
    If UserAnswer = vbYes Then rng.Interior.Color = vbYellow
  Else
    MsgBox "No duplicate cell values were found"
  End If

End Sub

**Note this code does not highlight the initial instance of a duplicate value. Only the 2nd instance and beyond are highlighted.

How To Delete Duplicate Data From Your Spreadsheet

Method 1: Use the Remove Duplicates Button

Did you know there is a dedicated button to remove duplicates in the Excel Ribbon? This is a really awesome functionality that can save you a ton of time. All you need to do is navigate to the Data tab in your Excel Ribbon. You can then click the Remove Duplicates button and fill out the dialog box to remove duplicates according to your specific needs. 

Remove Duplicates Ribbon Button

You can also access the Remove Duplicates button within the Table Tools - Design Ribbon tab if you are working with an Excel Table object.

Remove Duplicates Button with Excel Tables

Method 2: Using VBA Coding

The following VBA code shows how you can programmatically delete duplicate rows within your selected cell range without having to manually covert the range into a table. Don't worry, it will ask you if you are certain you want to delete the duplicate rows before permanently cleansing your data.

Sub DeleteDuplicates()
'PURPOSE: Delete any duplicate rows based on analyzing first column in selected range
'SOURCE: www.TheSpreadsheetGuru.com

Dim rng As Range
Dim rngFind As Range
Dim cell As Range
Dim DupAddresses As String
Dim SearchList As String
Dim Delimiter As String

'Setup Variables
  Set rng = Selection
  Delimiter = "-;;-"

'Loop through each cell in selection
For Each cell In rng.Columns(1).Cells
  'Does cell have value?
    If cell.Value <> "" Then
      'Has value been searched for yet?
        If InStr(1, SearchList, cell.Value & Delimiter) = 0 Then
          SearchList = SearchList & cell.Value & Delimiter
          
          Set rngFind = rng.Find(what:=cell.Value, LookIn:=xlValues, _
            lookat:=xlWhole, searchdirection:=xlNext)
        
          If Not rngFind Is Nothing Then
            'Record first instance found
              FirstAddress = rngFind.Address
              
            'Find any next instances of value
              Do
                Set rngFind = rng.FindNext(rngFind)
                If rngFind.Address = FirstAddress Then Exit Do
                Set rngFind = rngFind.Resize(1, rng.Columns.Count)
                DupAddresses = DupAddresses & rngFind.Address & ","
              Loop
              
          End If
        End If
    End If
Next cell

'Report Results
  If DupAddresses <> "" Then
    Set rng = Range(Left(DupAddresses, Len(DupAddresses) - 1))
    rng.Select

    UserAnswer = MsgBox(rng.Count & " duplicate values were found," _
      & " would you like to delete any duplicate rows found?", vbYesNo)
    If UserAnswer = vbYes Then Selection.Delete Shift:=xlUp
  Else
    MsgBox "No duplicate cell values were found"
  End If

End Sub

Any Others I Overlooked?

Are there any other methods that Excel offers that are even easier than the methods in this article? Do you know a more simplistic approach to accomplish the tasks in my VBA macros? I want to hear your thoughts and learn from your expertise. Leave a note in the comments section below if you have any way to make the content in this article better! I look forward to reading your thoughts!!

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 :)

Top Microsoft Excel Add-ins You Should Consider Using

$
0
0
Top Popular Excel Add-ins Directory List

What Are Add-ins?

Add-ins for Excel are similar to the apps you can download and purchase for your smartphone. They are mini software applications that you install into Excel in order to provide integration, shortcuts, and tasks that are not available within the standalone Excel application. Add-ins are created mainly by third-party businesses or self-motivated users (like myself) to fill a void that seems to be missing within Excel's vast array of capabilities. Creating an add-in not only takes coding prowess in languages like VBA and XML, but it also requires an eye for a smooth intuitive user-interface to make the program "feel" like it is a natural part of Excel. If you can find add-ins that possess both of these characteristics, you can do absolute magic within Microsoft Excel.

Where Do I Find Add-ins?

The main purpose of this directory is to provide a one-stop list of high-quality and practical add-ins that you can use to increase your productivity and capabilities while using Microsoft Excel. Since there are so many Excel developers out there, it can be somewhat hard to find Excel add-ins, let alone decipher the good ones from the bad ones. 

This list is in no way a reflection of "my favorites" or a "guaranteed hit", as I have not used every single one of the add-ins within this list. This is simply a starting place to help get you in the right direction without having to scour all over the internet for days to determine your options.

I do encourage you to leave reviews within the Comments Section at the bottom of this page describing add-ins you have had good/bad experiences with. Please feel free to recommend add-ins that may have been left off this list that you think people should know about. Enjoy!

  Top Excel Add-ins - Swiss Army Knife Addins

These kinds of add-ins just flat do a bunch of things. They contain general purpose functionalities that can be used in pretty much any spreadsheet you are working with. With these kinds of add-ins I usually find myself only using a few of the functionalities on a regular basis, but they sure do help make life easier! Below are some of the more popular Excel add-ins that will provide you with a whole ribbon tab worth of extra functionalities.


ASAP Utilities

Claimed to be "The most popular add-in for Excel users." ASAP Utilities is a powerful Excel add-in that fills the gaps in Excel with over 300 features. You can learn more about this Excel add-in by visiting the ASAP Utilities Page.

Trial Available? Yes
Original Release Date: 1999
Developer: Bastien Mensink

ASAP Utilities Excel Add-in

AbleBits Utility Pack

A suite of Excel add-ins that can perform various tasks. Examples include

  • Merging Excel Workbooks
  • Removing Duplicates
  • Combine Duplicate Rows
  • Remove Spaces, Change Cases
  • Sum or Count Cells by Color

You can learn more about this Excel add-in by visiting the AbleBits Sales Page.

Trial Available? Yes
Developer: Add-in Express Ltd

AbleBits Utility Pack Excel Add-in AbleBits Utility Pack Excel Add-in

Ribbon Commander

Ribbon Commander takes a new spin on Excel Add-in functionality. It acts as its own framework that allows the Excel Ribbon to be completely dynamic, which allows developers to create add-ins that were once thought to be impossible. Ribbon Commander comes with a bunch of individual add-ins that can be downloaded for free within it's Add-in Manager. You can learn more about this Excel add-in by visiting the Ribbon Commander Sales Page.

Trial Available? Yes
Developer: Ilyda Ltd

The Ribbon Commander Add-in Manager where you have access to a bunch of useful add-ins with the click of a mouse

The Ribbon Commander Add-in Manager where you have access to a bunch of useful add-ins with the click of a mouse


XL Tools Add-in

A suite of various Excel productivity tools. Examples Include Pop-up Calendars, Version Control, Data Cleaning, Combine Cell Data, and many more. You can learn more about this Excel add-in by visiting the XL Tools Sales Page.

Trial Available? Yes
Developer: WavePoint Co

XL Tools Excel Add-in   Top Excel Add-ins - Productivity & Ultities Addins

Productivity forms of Excel Add-ins do a specific task to help speed up what you are working or provide an easier solution than what is the norm within the Excel application. Here are some great solutions that will speed up specific tasks that might currently put a strain on your work day.

PivotPal Add-in

Supercharge your pivot tables with the PivotPal add-in. This Excel add-in provides tons of great Pivot Table related features that will make it easier and faster to modify your pivots. You can learn more about this Excel add-in by visiting the PivotPal Sales Page.

Trial Available? No
Developer: Excel Campus


E2P Add-in

This Excel add-in allows you to automate the painful task of copy & pasting your charts and tables from Excel into PowerPoint. You can learn more about this Excel add-in by visiting the E2P Sales Page.

Trial Available? Yes
Original Release Date: 2015
Developer: Guru Solutions (me!)

E2P Excel PowerPoint Add-in

Password Recovery Add-in

The Password Recovery Add-in allows you to remove passwords from VBA projects and Excel Worksheets that you have lost the passwords to. The Add-ins is packaged with a Microsoft Word and Microsoft PowerPoint version as well. You can learn more about this Excel add-in by visiting the Password Recovery Sales Page.

Trial Available? No
Developer: Guru Solutions (me!) & Spreadsheet1

Password Recovery Excel Add-in   Top Excel Add-ins - Chart Creation & Modification Addins

Peltier Tech Chart Utility 3.0 Add-in

This add-in is probably the most popular in its category. The variety of extra chart types available with this add-in is truly phenomenal. You can create Box Plots, Histograms, Paretos, and many more with a few click within the add-in. If you love using these advanced charting forms but hate the hassle of setting them up, the Peltier Tech Chart Utility add-in is definitely for you! You can learn more about this Excel add-in by visiting the Peltier Tech Chart Utility Sales Page.

Trial Available? No
Developer: Peltier Technical Services

Peltier Tech Chart Utility Excel Add-in

Chart-Me Add-in

The Chart-Me add-in is an advanced charting tool that allows you to create very intricate and complex charts through it's interface. Some examples include Contribution Margin analysis, ROI Trees, YTD Variances, and P&L Statements. You can learn more about this Excel add-in by visiting the Chart-Me Sales Page.

Trial Available? Yes
Developer: Hi-Chart

Chart Me Excel Add-in

X-Y Chart Labeler Add-in

This is a great little add-in that helps interacting with those pesky chart labels a whole lot easier. You can download this add-in for free on the X-Y Chart Labeler Sales Page.

Trial Available? This add-in is FREE
Developer: Apps Pro

X-Y Chart Labeler Excel Add-in   Top Excel Add-ins - Formatting & Design Addins

Dashboard Tools Add-in

This Excel Add-in allows you to plan out your dashboards with pre-created modules. It will also create fancy callouts and icons that you can use to make your Excel dashboards look like they came straight out of a graphic designers hands. You can learn more about this Excel add-in by visiting the Dashboard Tools Sales Page.

Trial Available? No
Developer: DataPig Technologies

Excel Dashboard Tools Add-in

myBrand Add-in

The myBrand Excel add-in allows you to integrate your personal or corporate brand colors into your Excel Ribbon. This app allows you to create custom formatting presets with whatever colors you need. You can also import up to 3 logos/images directly from your Excel Ribbon. This is the ultimate tool to incorporate your company-specific brand formats into Excel. You can learn more about this Excel add-in by visiting the myBrand Sales Page.

Trial Available? Yes
Developer: Guru Solutions


CF Shapes Add-in

CF Shapes allows you to create beautiful and responsive workbook dashboards using conditionally formatted shape objects. You can learn more about this Excel add-in by visiting the CF Shapes Sales Page.

Trial Available? Yes
Developer: Brad Edgar/Ryan Wells

Enter a URL to resolve. CF Shapes Excel Add-in
Top Excel Add-ins - Complimentary Utility Applications

There are also tools available that are standalone pieces of software but do great things to increase Excel's capabilities. These forms of Excel software tools are often overlooked because they do not integrate directly into Excel (and therefore cannot be called "add-ins"). Here are some great utility tools that fit into this category.


XL Styles Tool

This is a great utility tool for Excel that can greatly clean up an excel file. It removes unused cell styles and named ranges that contain errors or are hidden. This can greatly reduce the file size of a bloated file and reduce the chance of file corruption. This program is not available on the Microsoft App Store and you can learn more about the program by visiting the XL Styles Tool Sales Page.

Trial Available? No, This Is Free!
Developer: XL Geek


Unviewable Plus

Unviewable + is a great app for VBA add-in developers to protect their IP from potential hackers or re-distributers. This application can take your VBA add-in and apply various levels of protection to prevent users/customers from viewing the VBA source code. The application only takes a few seconds to run and has worked great for me and the add-ins I sell for TheSpreadsheetGuru. You can learn more about this application by visiting my review of Unviewable Plus.

Trial Available? No
Developer: Spreadsheet1

Unviewable Plus VBA Protection App

Custom UI Editor

The Custom UI Editor is a developer tool that allows you to easily create proper XML code for Excel's Ribbon Interface. You can learn more about this program by visiting the CustomUI Editor Download Page.

Trial Available? No, This Is Free!
Developer: OpenXMLDeveloper.org

Custom UI Microsoft Ribbon Editor

What Do You Think?

Hopefully this little add-in directory was helpful in bringing to light some great tools available for Excel. Like I said, I have not used very single one of the add-ins listed in the article, so I would love for you to leave an honest review about some of the tools you have used to help other visitors decide if an add-in is right for them. I look forward to reading about your recommendations and experience in the comments section below!

My First Microsoft Excel MVP Award!

$
0
0
Microsoft Excel MVP Award TheSpreadsheetGuru Blog

On July 1st, 2016 I received an email from Microsoft congratulating me on being awarded the Microsoft Excel MVP award for 2016. I was the only new person in the Excel category to receive the award out of the list of winners and I had to reread the email quite a few times before my mind could accept that I was now officially part of an amazing group of Excel users from across the world.

Chris Newman - Microsoft Excel MVP Award 2016

Since there is never a feeling like your first, I wanted to take time and document my experience to (1) selfishly remind myself of what it felt like, (2) thank those who have helped me get to where I am today, and (3) let you know how the program works and maybe how you too can one day be awarded this prestigious award from Microsoft Corporation.

A Special Thank You

I want to first thank Microsoft for considering my work in the Excel online community worthy of recognition. The very fact that Microsoft dedicates resources to recognize outside contributors, shows the value they place on their customers and developers. I also want to give a special thank you to Zack Barresse for nominating me for this award.

I would also like to take a moment and thank all of the other Excel bloggers that I have interacted with and even spent time chatting with over the years. I have never been part of a collective where it was so easy to interact with any level of the community, from long-time veterans to full-time consultants. The fact that so many people take time to help each other solve problems is a great testimony to how healthy the Excel community is. I would like to call a few people out by name whom I have spent many hours interacting not only on Excel-relate topics but everything from website building to brainstorming ways to turn the impossible into the possible. I've truly enjoyed getting know know and work with you over the past few years!

There are many more content creators and plain ol' Excel-users out there who I've had interactions with through my email newsletter, online forums, and the comments section of this very blog over the years. I am so thankful to have learned from you and hopefully I have been able to provide you all with some value as well. 

I also want to take a moment and thank my beautiful wife Stephanie for all her support as I have built and run this website. As you can imagine with a full-time day job, hours after work are few and far between. The fact that she is willing to let me spend time working on this site always amazes me and I'm so thankful to have a life-long partner who understands and supports my passions.

And finally, I want to thank you all, MY READERS!!!

Without you, this award would not have been given to me. Thank you for all the support, the kind words, suggestion on making my published solutions better, and yes even all you grammar police who make my articles flow much better! The only way I can truly show my appreciation is to continue to share my knowledge and experiences in the corporate world and I pray I am able to do that for many years to come!

What Is A Microsoft MVP?

If you are reading this and have absolutely know idea what being an "MVP" is, I can fully relate. When I started really digging into Excel 5 to 6 years ago many of the websites I studied were run by these "mystical" MVPs (ie Chandoo, JKP, Ron de Bruin, MrExcel, Chip PearsonDataPigTech -- just to name a few). I always figured based on the wealth of knowledge these particular folks were able to generate, that they must have gone through a special program or passed some sort of crazy test to get the award. That couldn't be further from the truth.

Absolutely anyone can be an MVP in a Microsoft category if they genuinely want to help others and put in some effort. Microsoft gives out these awards every quarter based on submitted nominations and they analyze how much VALUE you are bringing to the online community as a whole. That means you can create a tutorial blog, you could run a tips email newsletter, or you could just spend your spare time helping others on an online forum. There are many ways outside of being an Author or Consultant that can propel you to get a nomination.

To sum it up, Microsoft describes their MVPs as follows:

“Microsoft Most Valuable Professionals, or MVPs, are community leaders who’ve demonstrated an exemplary commitment to helping others get the most out of their experience with Microsoft technologies. They share their exceptional passion, real-world knowledge, and technical expertise with the community and with Microsoft.”

What Does Becoming An MVP Mean?

The MVP award is given based on past accomplishments and absolutely nothing is expected of you going-forward if you are given the award. For the year that you have MVP status, you are given a whole slew of Microsoft Software subscriptions, access to webinars presented by the Microsoft Dev Team, and a ticket to the Microsoft MVP Summit at Microsoft's Headquarters where you get behind-the-scenes access to what they've been working on.

If you would like to learn more about this award and all that it entails, ExcelTV interviewed one of the MVP Community Involvement Team Members in a video posted here.

Some Closing Thoughts

It is an unbelievable feeling to have put in so many hours of work over the past few years and to be able to help so many people across the world with problems they face. I can remember not too long ago, entering the corporate world after earning my MBA and not having once used a VLOOKUP function. I knew nothing about VBA or writing computer code and I definitely had no understanding of how to design a reusable spreadsheet model. I can definitely say, the sole driver of my self-taught education in Excel was my mentality of "Excel can do anything".

I can remember working VBA automations early on without any sign of it being possible via a Google search. My commitment to not give up and to not be afraid to ask for help provided me with the ability to always come up with a solution (and learn about 5 more new things along the way!). This mentality definitely helped drive my decision to create this Excel blog and was a message I wanted to promote throughout its pages. That is why at the end of every article I write, I have a message that points you to my strategies to getting the answer to your excel questions. While I may only be one man with a few hours in the evening to help out, there are millions of Excel users throughout the world who are ready and willing to help you become better and that is why I absolutely love the Excel online community!

~ Chris


Top Online Excel & VBA Courses 2016

$
0
0
Top Online Excel Courses.png

Choices, Choices, & MORE Choices!

With so many educational options available on the internet these days, it can be overwhelming to try and find the perfect course that is going to take your Excel skills to the next level. A good rule of thumb that I always use with any internet purchase is: you get what you pay for!

Sure you can search through an online "course mall" like Udemy or Lynda but honestly, how much are you expecting to get out of a $10 course? I've found through the vast array of courses I've taken over the years in photography, website building, business development, and yes Excel too....that the most beneficial & high-quality courses come directly from the teachers themselves.

Why is this you might be wondering? Because the success of their students correlates directly with the success of their business. They aren't relying on cheap marketing tactics to sell their courses to as many people as possible. They are targeting people who want to invest in themselves and at the same time are able to satisfy those students' high expectations.

So, I've gone ahead and created this post to round up some of the best quality courses currently available on topics like creating dashboards, mastering Pivot Tables, and figuring out how to write custom VBA code. I know that search engines can sometimes not show quality results because companies with large budgets are able to pay Google for search rankings. My intent is to have an easy to find course directory that will serve as a good starting point for laying out a bunch of choices for the Excel course that is right for you!

Leave Your Own Review

Have you already taken one of these online courses? Let us all know what you thought of the course in the comments section at the end of this post! I will definitely admit I have not taken all of these courses (although I was granted access to view the course modules included in them so I could ensure the quality of the content). An honest review from you would be so helpful in helping others decide on the right course for them, so take a few minutes and let us know how your experience went!


DISCLAIMER: I always want to be fully transparent with you, so I'm letting you know that some of the course creators listed below are willing to pay me a small referral fee for sending you in their direction. This in no way influenced my decision to add them to the list, as I even turned down listing a few courses because I did not believe their quality of content was worth including to this list. So if you want to send a few "thank you" dollars my way to help support this website, click the links in this article instead of manually typing in their web address.


Increasing Your Overall Excel Skills

Hired with Excel: What Every Analyst Needs to Know

This is a course taught by George Mount and is geared towards helping regular/basic Excel users transform into highly sought after Analysts. In his 5-Module course, George covers Vlookups, Pivot Tables, Real World examples, and interview tips. Learn More About This Excel Course...

George Mount Excel Spreadsheet Instructor

Cost: $150
Instructor Accent: American
Guarantee: 30-day money back 

 

Become An Excel Ninja

This course is taught by Rishabh Pugalia of YodaLearning.com. His course has the objective of taking you from an Excel beginner to an advanced user with 11-hours of video training. The training covers helpful shortcuts, formulas, and hidden tricks to help make you a NINJA as work. Learn More About This Online Excel Course...

Rishabh Pugalia Excel Spreadsheet Instructor

Cost: $100
Instructor Accent: Indian
Guarantee: 30-day money back 

 

Xtreme Pivot Tables Course

This Excel course is taught by John Michaloudis of MyExcelOnline.com. I can easily say this course is the most comprehensive educational tool on Pivot Tables. If you want to know all things Pivot Tables, this would be the course you want to check out with 14-Modules of content. Learn More About This Online Excel Course...

John Michaloudis Excel Course Instructor

Cost: $100-$300
Instructor Accent: Australian
Guarantee: 30-day money back

 

Core Formula

This Excel course is taught by Dave Bruns of ExcelJet.com. Dave worked in the online education space for quite a few years before starting his own business. His training covers everything you need to know about using Excel formulas effectively. This includes Referencing, Dynamic Named Ranges, working with text & dates, statistics, lookups, and much more! Learn More About This Online Excel Course...

David Bruns Excel Spreadsheet Instructor

Cost: $200
Instructor Accent: American
Guarantee: 30-day money back


Creating Interactive Dashboards

Excel Dashboard Course

A course taught by Excel MVP Mynda Treacy of MyOnlineTrainingHub.com. This training includes over 9 hours of video tutorials plus another 3 hours of (optional) related Excel training that will fill in any gaps in your Excel knowledge on topics like PivotTables, Lookup functions, Macros and more. Five different Excel dashboards are given to you with lots of techniques built-in that you can take with you and incorporate into your own dashboard spreadsheets. Learn More About This Online Excel Course...

Mynda Treacy Excel Course Instructor

Cost: $200-$400 (plus bundling options)
Instructor Accent: British
Guarantee: 30-day money back

 

Excel School & Dashboards

This online course is taught by Excel MVP Chandoo who runs one of the top Excel blogs in the world Chandoo.org. This "school" was designed to not only cover all the Excel basics that any analyst needs to become Awesome in Excel, it also has a Dashboard building component that takes your Excel skills to another level! This offering has over 24 hours of general Excel lessons covering formulas, conditional formatting, Pivot Tables, Charts and much more. But it also has 8 hours of video dedicated solely to creating dashboards. Learn More About This Online Excel Course...

Chandoo Excel Spreadsheet Instructor

Cost: $100-$300
Instructor Accent: Indian
Guarantee: 30-day money back


Learning Automation With VBA Macro Coding

VBA Pro Course

This is a course taught by Excel MVP Jon Acampora of ExcelCampus.com. Jon has put together a 10-Module course covering all aspects of learning how to write VBA code to automate your Excel work. Some module topics include Coding 101, Looping, Error Handling, & even creating your own custom add-ins.

This course is not currently accepting students, but you can join the waiting list and enjoy a few free lessons while you wait for the course to open. I try to let my email subscribers know when I hear Jon is enrolling new students. Learn More About This Online Excel Course...

Jon Acampora Excel Course Instructor

Cost: $300-$400
Instructor Accent: American
Guarantee: 30-day money back

 

Excel Macros for Beginners Course

This is a course taught by Allen Wyatt who has operated an Excel tips newsletter for over 18 years at ExcelRibbon.Tips.Net. This 15-Module course covers absolutely everything about VBA including topics that cover understanding VBA functions, searching and replacing, debugging your macros, and much more. Learn More About This Online Excel Course...

Allen Wyatt Excel Spreadsheet Instructor

Cost: $250-$450
Instructor Accent: American
Guarantee: 30-day money back

Allen only opens up his online course about once a quarter so you will have to try to keep track of when he is offering registration for the course. I try to send out announcements through my newsletter when his course opens up for registration, so feel free to sign up to TheSpreadsheetGuru Newsletter to stay in the know.

Registration is currently open! 20% off early bird discount through September 22nd, 2016. Enrollment closes September 29th, 2016.


Power Query/Power Pivot

Power Pivot Course 

A course taught by Excel MVP Mynda Treacy of MyOnlineTrainingHub.com. This training includes over 5 hours of video training covering how you can use Power Pivot to mange enormous amounts of data right inside of Excel. You will learn how to:

  • Import millions of rows of data from virtually any source
  • Create relationships
  • Build Interactive Reports
  • Write in this DAX (Data Analysis Expressions) formula language

Learn More About This Online Excel Course...

Mynda Treacy Excel Spreadsheet Instructor

Cost: $150-$400 (plus bundling options)
Instructor Accent: British
Guarantee: 30-day money back

 

Excel Power Query Course 

A course taught by Excel MVP Mynda Treacy of MyOnlineTrainingHub.com. This training includes over 4 hours of video training covering how you can use Power Query to pull in your data, clean your data, and report out your data through an automated system within Excel. The best part is there is no VBA coding required to automate these tasks! Learn More About This Online Excel Course...

Mynda Treacy Excel Course Instructor

Cost: $100-$300 (plus bundling options)
Instructor Accent: British
Guarantee: 30-day money back

 

Did I Miss Any Great Online Excel-based Courses?

If you have taken an amazing Excel course recently that didn't make it on this list, please let us all know where you took it and what you liked about it. I would like to keep course recommendations to actual students and not course creators, so if I see any signs of self-promotion in the comments section I will block you :)

Hopefully, this information was helpful and will guide you to the course that fits your needs! Until next time!

~ Chris

Prevent Microsoft Office Add-ins From Disappearing From The Ribbon Interface

$
0
0
Blog Post Banner (hdr).png

This year (July 2016) Microsoft decided to heighten it's security features and block files that are downloaded from the internet or another computer by default. With regular files like a .xlsx or .pptx there is a prompt that notifies you the file is currently being blocked. Unfortunately, Microsoft was not kind enough to do the same thing with add-in files (.xlam or .ppam). Hence, leaving a TON of users scratching their heads as to why add-ins keep disappearing from their ribbon. 

If you have recently downloaded an add-in file from this site or any other, you will want to follow one of the laid out solutions described below.

If you are a video person, Jon Acampora (ExcelCampus.com) created a great little video that explains what I will be writing in this article.

Please note that the following steps are based on using the Excel Application. Other Microsoft applications may have slightly different steps to get to the end result.

Option 1: Make Parent Folder A Trusted Folder

This option is most preferred as any file saved into a trusted folder will be unblocked without changing each individual file's properties.

  1. Copy your folder path (ie Ctrl +C)
  2. Go To File > Options
  3. Select Trust Center > Trust Center Settings
  4. Go to Trusted Locations and select Add New Location
  5. Paste in your folder path (ie Ctrl + V) and click OK (3 times to close out of all the dialog boxes)
Click to enlarge

Click to enlarge

Option 2: Check Unblock Property*

  1. Right-click the add-in file
  2. Click Properties
  3. Check Unblock
  4. Click OK

*This option is not preferred because if an updated file is sent to you, you will have to remember to repeat the steps to unblock the file.

Hopefully, this solution gets your add-ins staying in place! In case this did not solve your issue, here are a couple more articles on the topic that may be of help:

Dynamically Populating VBA Array Variables To Store Lists of Data

$
0
0
Dynamically Fill VBA Array Variables

What Are Arrays?

Arrays are a variant type variable that you can use in VBA coding to store a list of data. Think of it as a mini-spreadsheet inside of a single variable. You store data into an array by referring to a reference number that corresponds with the location that the piece of data is positioned in.

Below is an example of an array that is holding all the month names within a year. Notice that the reference number starts at zero instead of one.

VBA Array Variables one dimensional example

You can also have multi-dimensional arrays. Below is a two-dimensional array that looks much like a typical spreadsheet is setup. You can create even more dimensions if you need to (ie think "Data Cube"), but in my experience two dimensions is the max that a typical person will ever need. 

VBA Array Variables two dimensional example

Now that you've had a quick overview of what arrays are, let's get into the meat of this article and learn various ways to dynamically resize these variables to fit all of your data.

Method 1: Resizing First

This method resizes the array to the size of your target data or list before actually placing the values inside the array. This can be a good option if you know beforehand how many items you need to store.

Sub PopulatingArrayVariable()
'PURPOSE: Dynamically Create Array Variable based on a Given Size

Dim myArray() As Variant
Dim DataRange As Range
Dim cell As Range
Dim x As Long

'Determine the data you want stored
  Set DataRange = ActiveSheet.UsedRange

'Resize Array prior to loading data
  ReDim myArray(DataRange.Cells.Count)

'Loop through each cell in Range and store value in Array
  For Each cell In DataRange.Cells
    myArray(x) = cell.Value
    x = x + 1
  Next cell

'Print values to Immediate Window (Ctrl + G to view)
  For x = LBound(myArray) To UBound(myArray)
    Debug.Print myArray(x)
  Next x

End Sub

Method 2: Resizing As You Go

This VBA method resizes the array variable right before storing each item. The key command here is "Preserve". This tells the code to keep all the stored items in the Array while increasing it's storage capacity. If you forgo having Preserve in your code immediately after you ReDim, the array variable will wipe clean of data previously stored in it before re-dimensioning.

Sub PopulatingArrayVariable()
'PURPOSE: Dynamically Create Array Variable based on a Given Size

Dim myArray() As Variant
Dim DataRange As Range
Dim cell As Range
Dim x As Long

'Determine the data you want stored
  Set DataRange = ActiveSheet.UsedRange

'Loop through each cell in Range and store value in Array
  For Each cell In DataRange.Cells
    ReDim Preserve myArray(x)
    myArray(x) = cell.Value
    x = x + 1
  Next cell

'Print values to Immediate Window (Ctrl + G to view)
  For x = LBound(myArray) To UBound(myArray)
    Debug.Print myArray(x)
  Next x

End Sub

Method 3: Creating From A Delimited String

Another way you can populate an array variable is through a delimiter. A delimiter is simply a designated set of character(s) that separates out your values. Have you ever heard of a CSV file? CSV stands for "Comma-Separated Values" where a comma symbol tells your computer how to separate each value apart from one another.

You can use this same concept to make your own delimited string or (more realistically) read a delimited string exported from your database software to populate the array. In my below example code I am taking a set range and turning it into a delimited string with the characters ";|;" separating each value. 

Sub PopulatingArrayVariable()
'PURPOSE: Dynamically Create Array Variable based on a Given Size

Dim myArray As Variant
Dim myString As String
Dim DataRange As Range
Dim cell As Range
Dim x As Long

'Determine the data you want stored
  Set DataRange = ActiveSheet.Range("A1:A100")

'Loop through each cell in Range and store value in delimited string
  For Each cell In DataRange.Cells
    myString = myString & ";|;" & cell.Value
  Next cell

'Remove first delimiter from string (;|;)
  myString = Right(myString, Len(myString) - 3)
  
'Create an array with the Split() function
  myArray = Split(myString, ";|;")

'Print values to Immediate Window (Ctrl + G to view)
  For x = LBound(myArray) To UBound(myArray)
    Debug.Print myArray(x)
  Next x

End Sub

If you are already starting with a delimited string, use this simplified VBA code to accomplish the same thing.

Sub PopulatingArrayVariable()
'PURPOSE: Dynamically Create Array Variable based on a Given Size

Dim myArray As Variant
Dim myString As String
Dim x As Long

'Store delimited string to a variable
  myString = "Apple;|;Orange;|;Pear;|;Peach;|;Grapes"
  
'Create an array with the Split() function
  myArray = Split(myString, ";|;")

'Print values to Immediate Window (Ctrl + G to view)
  For x = LBound(myArray) To UBound(myArray)
    Debug.Print myArray(x)
  Next x

End Sub

Method 4: Pulling From An Excel Table [My Favorite Option!]

This is my favorite way to populate array variables dynamically because it has a user-interface aspect to it (ie it allows you to make changes to the inputs without rewriting the code). Now you may be thinking to yourself that a couple of the VBA snippets above are pulling from ranges that you could easily substitute with a named range in your code. This is true, but tables have the auto-expanding feature that can make you 100% certain from a visual perspective that you are picking up all your values.

You will want to note that when you size an Array variable from a Range or Table, the first reference number will be a One instead of the typical Zero.

Sub PopulatingArrayVariable()
'PURPOSE: Dynamically Create Array Variable based on a Single Columned Table

Dim myArray() As Variant
Dim myTable As ListObject
Dim cell As Range
Dim x As Long

'Set path for Table variable
  Set myTable = ActiveSheet.ListObjects("Table1")
  
'Create Array List from Table
  TempArray = myTable.DataBodyRange.Columns(1)
  
'Convert from vertical to horizontal array list
  myArray = Application.Transpose(TempArray)

'Loop through each item in the Table Array (displayed in Immediate Window [ctrl + g])
  For x = LBound(myArray) To UBound(myArray)
    Debug.Print myArray(x)
  Next x

End Sub

Any Other Methods?

Are there any other methods you use to populate arrays dynamically? I would love to hear from you in the comments section below and maybe I can add some other options to the ones I've already discussed in the article.

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 :)

Use Yahoo! Finance To Pull Stock Information Into Excel

$
0
0
Stock Price Data From Yahoo! Finance With Microsoft Excel Spreadsheets

I've been playing around with building some Stock Tracking tools for Excel and I've learned a lot about how to query data from Yahoo! Finances API to get it into Excel while it's all fresh in my memory, I figured I would take some time and document some of the techniques I've been using in my spreadsheets.

Breakdown Of The Yahoo! Finance Query URL

The premise behind how you query stock information in your web browser ultimately boils down to the URL address.  Here is the standard URL address formula with two inputs (the Ticker Symbol and the Data Type).

http://finance.yahoo.com/d/quotes.csv?s= [Ticker Symbol] &f= [Data Type]

A Few Examples

To get this data from a web address into an Excel spreadsheet, we can use the WEBSERVICE() function. I'll also wrap a NUMBERVALUE() function around to convert the import text from Yahoo! Finance into a numerical value we can use inside Excel.

Example 1: Pull The "Current Stock Price" for Microsoft's Stock

=NUMBERVALUE(WEBSERVICE("http://finance.yahoo.com/d/quotes.csv?s=MSFT&f=l1"))

Example 2: Pull The "Current Dividend" for Microsoft's Stock

=NUMBERVALUE(WEBSERVICE("http://finance.yahoo.com/d/quotes.csv?s=MSFT&f=d"))

Example 3: Pull "% change From 52 Week Low" for Microsoft

This one is a little bit trickier because the results from the url have a plus sign or a negative sign in front of the resulting % change which the NUMBERVALUE() function does not like. In the following formula, I am taking the result from Yahoo! finance and removing the first character (ie +/-) from the result.

=NUMBERVALUE(REPLACE(WEBSERVICE("http://finance.yahoo.com/d/quotes.csv?s=MSFT&f=j6"),1,1,""))

Example 4: Link your Ticker Symbols to a Spreadsheet Cell

If you want to use the same formula for a bunch of different ticker symbols, you can link your formula using a cell reference. Here is the same formula from Example 1, however it is now point to a ticker symbol in cell A2.

=NUMBERVALUE(WEBSERVICE("http://finance.yahoo.com/d/quotes.csv?s=" & A2 & "&f=l1"))

Data Type Tables

Yahoo! has a whole collection of data points you can pull about a specific ticker symbol. Here is a list of the variables and what they pull in:

Stock Pricing

Averages

VariableDescription
aAsk
bBid
b2Ask (Real-time)
b3Bid (Real-time)
pPrevious Close
oOpen
c1 Change
c Change & Percent Change
c6 Change (Real-time)
k2 Change Percent (Real-time)
p2 Change in Percent
d1 Last Trade Date
d2 Trade Date
t1 Last Trade Time

Dividends

VariableDescription
yDividend Yield
dDividend per Share
r1Dividend Pay Date
qEx-Dividend Date
VariableDescription
c8 After Hours Change (Real-time)
c3 Commission
g Day’s Low
h Day’s High
k1 Last Trade (Real-time) With Time
l Last Trade (With Time)
l1 Last Trade (Price Only)
t8 1-Year Target Price
m5 Change From 200 Day Moving Average
m6 % Change From 200 Day Moving Average
m7 Change From 50 Day Moving Average
m8 % Change From 50 Day Moving Average
m3 50-Day Moving Average
m4 200-Day Moving Average

Volume

VariableDescription
v Volume
a5 Ask Size
b6 Bid Size
k3 Last Trade Size
a2 Average Daily Volume

52-Week Pricing

Ticker Related Information

VariableDescription
k 52-Week High
j 52-Week Low
j5 Change From 52-Week Low
k4 Change From 52-Week High
j6 Percent Change From 52-Week Low
k5 Percent Change From 52-Week High
w 52-Week Range
g1 Holdings Gain Percent
g3 Annualized Gain
g4 Holdings Gain
g5 Holdings Gain Percent (Real-time)
g6 Holdings Gain (Real-time)
VariableDescription
i More Info
j1 Market Capitalization
j3 Market Cap (Real-time)
f6 Float Shares
n Name
n4 Notes
s Symbol
s1 Shares Owned
x Stock Exchange
j2 Shares Outstanding

Financial Ratios

VariableDescription
e Earnings per Share
e7 EPS Estimate Current Year
e8 EPS Estimate Next Year
e9 EPS Estimate Next Quarter
b4 Book Value
j4 EBITDA
p5 Price / Sales
p6 Price / Book
r P/E Ratio
r2 P/E Ratio (Real-time)
r5 PEG Ratio
r6 Price / EPS Estimate Current Year
r7 Price / EPS Estimate Next Year
s7 Short Ratio

Miscellaneous

VariableDescription
t7 Ticker Trend
t6 Trade Links
i5 Order Book (Real-time)
l2 High Limit
l3 Low Limit
v1 Holdings Value
v7 Holdings Value (Real-time)
s6 Revenue
w1 Day’s Value Change
w4 Day’s Value Change (Real-time)
p1 Price Paid
m Day’s Range
m2 Day’s Range (Real-time)

Refreshing The Formulas

As you might imagine, if you are pulling realtime data from Yahoo! Finance, Excel is not going to recalculate your WEBSERVICE() formulas every second. Therefore, you will need to manually recalculate your sheet (keyboard shortcut F9) in order to refresh your formulas.

VBA Macro To Pull Historical Data

Yahoo! Finance has a ton of historical data for stocks and harnessing VBA's automating power to pull this data in seconds can allow you to perform some unbelievable tailor-made analysis. Let's take this very simple setup in Excel where we have the Stock Ticker in Cell B2 and the Start/End date range you want to pull in Cell C4 and Cell F4 respectively. Also, the Excel Table is named "StockTable". 

VBA Macro Pull Historical Stock Prices From Yahoo! Finance

See if you can follow along with the VBA as it pulls data directly from Yahoo! Finance and places it into Excel. There is a little extra clean up you need to do since the query is pulled into excel as a CSV (comma separated values) data set.

ALSO NOTE: Through some testing, it seems you will need to have at least one extra column in your table (ie the black section in the image above) in order to retain the Table Object after the VBA performs the TextToColumns function. You can just leave this extra column blank if you do not need to perform any extra calculations.

Sub YahooFinanceQuery()
'PURPOSE: Pull Historical Stock Data From Yahoo! Finance
'SOURCE: www.TheSpreadsheetGuru.com

Dim EndDate As Date
Dim StartDate As Date
Dim StockTicker As String
Dim QueryURL As String
Dim QueryDataRange As Range
Dim QueryLocation As Range
Dim tbl As ListObject

'Optimize Code
  Application.ScreenUpdating = False
  Application.DisplayAlerts = False
    
'Query Parameters
  StartDate = Range("C4").Value
  EndDate = Range("F4").Value
  StockTicker = Range("B2").Value

'Store Table Object to a Variable
  Set tbl = ActiveSheet.ListObjects("StockTable")

'Determine Where To Place Query (Column Prior To Table)
  Set QueryLocation = tbl.Range(1, 1).Offset(0, -1)
  QueryLocation.EntireColumn.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
  Set QueryLocation = QueryLocation.Offset(0, -1)

'Delete all table rows except first row
  With tbl.DataBodyRange
    If .Rows.Count > 1 Then
      .Offset(1, 0).Resize(.Rows.Count - 1, .Columns.Count).Rows.Delete
    End If
  End With
  
'Create Web Address To Query Historic Stock Data
  QueryURL = "http://ichart.finance.yahoo.com/table.csv?s=" & StockTicker
  QueryURL = QueryURL & "&a=" & Month(StartDate) - 1 & "&b=" & Day(StartDate) & _
      "&c=" & Year(StartDate) & "&d=" & Month(EndDate) - 1 & "&e=" & _
      Day(EndDate) & "&f=" & Year(EndDate) & "&g=" & QueryLocation & "&q=q&y=0&z=" & _
      StockTicker & "&x=.csv"
  
'Pull Query Into Excel
  With ActiveSheet.QueryTables.Add(Connection:="URL;" & QueryURL, Destination:=QueryLocation)
    .BackgroundQuery = True
    .TablesOnlyFromHTML = False
    .Refresh BackgroundQuery:=False
    .SaveData = True
  End With
  
'Determine Stock Data Range
  ActiveSheet.UsedRange
  Set QueryDataRange = ActiveSheet.Range(QueryLocation, Cells(ActiveSheet.Cells _
    (ActiveSheet.Rows.Count, QueryLocation.Column).End(xlUp).Row - 1, QueryLocation.Column))

'Sort Data in Ascending Order
  ActiveSheet.Sort.SortFields.Clear
  
  ActiveSheet.Sort.SortFields.Add Key:=QueryDataRange, _
    SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    
  With ActiveSheet.Sort
    .SetRange QueryDataRange
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
  End With
  
'Delimit Stock Data into Table
  QueryDataRange.TextToColumns Destination:=QueryLocation.Offset(0, 2), DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
    Semicolon:=False, Comma:=True, Space:=False, other:=False

'Delete Yahoo! Finance Stock Query
  QueryLocation.EntireColumn.Delete

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

End Sub

Get The VBA Example File

If you need a little head start or are not comfortable with VBA quite yet, I have put together a great little example Excel file with the examples covered in this article.

As always, in order to download this or any example file from this website, you will need to be a subscriber of my free tips 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 :)

Use VBA To Automatically Adjust Your Charts Y-Axis Min and Max Values

$
0
0
Automatically Adjust Chart Y-Axis Limits Excel

Why Manually Adjust Your Y-Axis?

By default, Excel will automatically decide the minimum and maximum values of your vertical (Y) axis. For the most part this will visually work for graphing your data, but there are certain instances where Excel's guessing may make your chart look weird or prevent it from telling the story you are trying to portray. Let's look at a couple of examples to show you what I mean.

The Waterfall Chart Example

Waterfall charts are used to show causes for the ups and downs (variances) between two data points. They are very good ways to quickly display root causes for changes in metrics and are used quite frequently in the corporate world. 

The two charts below are the same exact charts except the one on the left has the minimum value for the Y-Axis starting at $0 while the one on the right has the minimum value starting at $450. It should be pretty apparent that the chart on the right with the $450 Y-axis starting point is much more presentable than the one starting at $0.

Now most chart experts would argue that even though the chart on the right looks more appealing, it skews the perception on how big of an impact the $10, ($5), and $20 changes are in relation to the $500 starting point. And this brings us to a fork in the road where you will need to make a decision based on your audience. If you are going to be presenting a chart to an audience of finance-minded executives or managers, chances are they are going to know how big of a deal a $10 change in your sales is. However, if you were a journalist writing a piece on the economy for the general public you might not want to risk this distorted view as some in your target audience may not be able to process both the visual and the data to come to a conclusion.

In case you were wondering, these charts were created with my Waterfall Chart Creator add-in for Excel. If you like Waterfalls you'll love this add-in (there's even a free trial!).

In case you were wondering, these charts were created with my Waterfall Chart Creator add-in for Excel. If you like Waterfalls you'll love this add-in (there's even a free trial!).

If you wanted to play it safe, you might display your chart with an added metric to right size the data. I would add percent change to the graphic as shown below.

Auto Adjust Y Axis Vertical Bounds

The Year-Over-Year Trends Example

There will be times as an analyst where you are not trying to create a pretty chart, you are just trying to simply "analyze" data! This can often times take the form of looking a seasonal trends over multiple years to ensure a forecast is directionally correct.

Let's take a look at the below two line charts that are analyzing crop yields (ie what percentage of your land created food you could sell). This might be useful if you are trying to determine if a 2016 forecast looks in line with historical trends.

Change Vertical Axis Limits In Microsoft Excel Graph

The problem that you might pick up on while looking at the first chart is depending on your data, it may be very difficult to look at the changes for the trended years. By changing your Y-Axis Min/Max (effectively zooming in), you can clearly see in October your 2016 forecast might need a little adjusting.

Again, if you were to present this chart you would need to have confidence that your audience is savvy enough to read the scale and realize the axis starts at 70% instead of 0%.

To bring attention, you could try highlighting the 70% with a box.

How Do I Manually Adjust The Y-Axis Min/Max?

Here are the steps:

  1. Select the Y-Axis
  2. Right-Click the highlighted Y-Axis and select Format Axis... from the menu
  3. Make sure you are within the Axis Options section of the Format Axis Pane
  4. Within the Bounds section, manually input your Minimum and Maximum axis limits

Getting VBA To Do The Work For You

Adjusting your minimum and maximum bounds to your chart axis is pretty straight-forward, however it can get rather cumbersome if your data is frequently changing (think dashboard) and you are required to keep adjust your axis bounds to make the chart useful.

This is where VBA can be extremely useful! Below is a VBA macro I created that will go throw all the charts on your worksheet and adjust the y-axis according to the minimum and maximum values within the charts specific data. There is even an input to add a little extra padding to your axis so the axis' bounds is a bit under or over your min/max data points.

Sub AdjustVerticalAxis()
'PURPOSE: Adjust Y-Axis according to Min/Max of Chart Data
'SOURCE: www.TheSpreadsheetGuru.com

Dim cht As ChartObject
Dim srs As Series
Dim FirstTime  As Boolean
Dim MaxNumber As Double
Dim MinNumber As Double
Dim MaxChartNumber As Double
Dim MinChartNumber As Double
Dim Padding As Double

'Input Padding on Top of Min/Max Numbers (Percentage)
  Padding = 0.1  'Number between 0-1

'Optimize Code
  Application.ScreenUpdating = False
  
'Loop Through Each Chart On ActiveSheet
  For Each cht In ActiveSheet.ChartObjects
    
    'First Time Looking at This Chart?
      FirstTime = True
      
    'Determine Chart's Overall Max/Min From Connected Data Source
      For Each srs In cht.Chart.SeriesCollection
        'Determine Maximum value in Series
          MaxNumber = Application.WorksheetFunction.Max(srs.Values)
        
        'Store value if currently the overall Maximum Value
          If FirstTime = True Then
            MaxChartNumber = MaxNumber
          ElseIf MaxNumber > MaxChartNumber Then
            MaxChartNumber = MaxNumber
          End If
        
        'Determine Minimum value in Series (exclude zeroes)
          MinNumber = Application.WorksheetFunction.Min(srs.Values)
          
        'Store value if currently the overall Minimum Value
          If FirstTime = True Then
            MinChartNumber = MinNumber
          ElseIf MinNumber < MinChartNumber Or MinChartNumber = 0 Then
            MinChartNumber = MinNumber
          End If
        
        'First Time Looking at This Chart?
          FirstTime = False
      Next srs
      
    'Rescale Y-Axis
      cht.Chart.Axes(xlValue).MinimumScale = MinChartNumber * (1 - Padding)
      cht.Chart.Axes(xlValue).MaximumScale = MaxChartNumber * (1 + Padding)
  
  Next cht

'Optimize Code
  Application.ScreenUpdating = True

End Sub

I will typically link this macro up to a button on the spreadsheet or assign it to a spreadsheet event (such as "Before Double-Click" or "Change"). That way you can get all your charts adjusted quickly without having to manually go in and execute the macro every time.

Here is a simple example of how you might trigger the AdjustVerticalAxis macro above through the Worksheet_Change event.

Private Sub Worksheet_Change(ByVal Target As Range)
'PURPOSE: Run AdjustVerticalAxis macro when Cell C2 is changed

If Target = Range("C2") Then Call AdjustVerticalAxis

End Sub

Get The VBA Example File

If you need a little head start or are not comfortable with VBA quite yet, I have put together a great little example Excel file with the VBA code covered in this article. The example workbook covers both a button triggered macro and a Event Triggered macro.

As always, in order to download this or any example file from this website, you will need to be a subscriber of my free tips 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 :)

Viewing all 117 articles
Browse latest View live