Showing posts with label Examples. Show all posts
Showing posts with label Examples. Show all posts

Wednesday, September 25, 2024

Generate A Random Number In Google Sheets

I was thinking about trying to transfer one of my most popular spreadsheet templates, Super Bowl Squares, from Excel to Google sheets. However, macros do not work in Google sheets. I was thinking about trying to recreate at least some of them, and the first problem to solve was how to make a random number generator script in Google Sheets.

Here's how you can create a Google Apps Script to generate random numbers between 0 and 9 in cells A1 to A9 without any repeats. 

Steps to Create the Google Apps Script:

  1. Open your Google Sheet.
  2. Click on Extensions in the menu.
  3. Select Apps Script.
  4. Delete any existing code in the script editor, and paste the following code:

function generateRandomNumbers() { // Create an array with numbers 0 to 9 var numbers = Array.from({length: 10}, (_, i) => i); // Shuffle the array for (var i = numbers.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); var temp = numbers[i]; numbers[i] = numbers[j]; numbers[j] = temp; } // Get the active spreadsheet and sheet var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); // Place the shuffled numbers in cells A1 to A9 for (var k = 0; k < 9; k++) { sheet.getRange(k + 1, 1).setValue(numbers[k]); } }
  1. Save the script by clicking the disk icon or pressing Ctrl + S. You can name it something like RandomNumberGenerator.
  2. Close the Apps Script editor.
  3. Back in your Google Sheet, go to Extensions -> Macros -> Import and then select your generateRandomNumbers function.
RandomNumberGenerator google apps script


How to Run the Random Number Generator Script:

  • To run the script, go to Extensions -> Macros -> generateRandomNumbers.
  • The script will place random numbers between 0 and 9 in cells A1 to A9, with no repeats.

If this is your first time running the script, Google Sheets may ask you for permission to run the script. Approve the permissions to proceed. 

In my templates, I make macros easy to use by running them from a button click. Yes, you can run the script from a button in Google Sheets too! Here’s how you can set it up:

Step 1: Create the Script

  1. Open your Google Sheet.
  2. Click on Extensions in the menu.
  3. Select Apps Script.
  4. Delete any existing code in the script editor, and paste the script provided above.
  5. Save the script by clicking the disk icon or pressing Ctrl + S.

Step 2: Add a Button to Google Sheets

  1. Insert a Drawing (for the Button):

    • Go to your Google Sheet.
    • Click on Insert -> Drawing.
    • Click on the Text Box icon in the Drawing toolbar and draw a text box.
    • Type in a label for your button, such as "Generate Numbers."
    • Format the text and shape as you like.
    • Click Save and Close. The button will now appear on your sheet.
  2. Assign the Script to the Button:

    • Click on the drawing (the button) you just created.
    • Click on the three vertical dots in the top right corner of the button, and select Assign script.
    • In the text box that appears, type the name of your script function, which is generateRandomNumbersInRow.
    • Click OK.

Step 3: Use the Button

  • Now, whenever you click the button, the generateRandomNumbersInRow script will run, and random numbers will be placed in the cells G3 to P3.

This provides a user-friendly way to trigger the script without needing to go through the menu every time. The first problem is solved! Onto the next one...

Monday, March 18, 2024

2024 March Madness Brackets and Basketball Squares

If you're looking for 2024 March Madness Brackets, no, I won't be posting any here or making my own. Once again, I will be using the best March Madness brackets in Excel, created by David Tyler (and I will continue to use his until he decides to no longer update them). They’re very polished and easy to use. There are only 68 teams in the field but the spreadsheet is already setup to handle up to 128 teams, if they expand in the future. There are two sheets: the bracket and the pool manager. Instructions are included but its very intuitive. Take a look:

 

As I’ve said countless times before, you can learn a lot by looking at Excel templates made by others. Here are 5 things I do when examining a new spreadsheet using David's March Madness brackets as example.

March Madness Squares

When I created my new Super Bowl Squares Unlimited spreadsheet for last month's football game, I had the goal in mind to be able to use the same sheet for other sports, like basketball. I tweaked my template a little and now you can use it for March Madness Squares!



There's multiple ways you could go about playing March Madness Squares:

1. Everyone keeps the same random numbers for every game
2. The random numbers change for every round
3. The random numbers change for every game

Here's a quick demo of how to use squares for basketball:



You can play either way with my spreadsheet. I designed it to be very versatile. Payout percentage can change per round as well. Update the settings how you want them then you click Generate Scoreboard once for every game, so 32 times in the first round. There are a lot of other options built in that can be ignored - it's all up to you!

Will you be playing 2024 March Madness Brackets, March Madness Squares, or both? Let me know in the comments below.

Friday, January 19, 2024

Girl Scout Cookie Tracking Spreadsheet Template

My daughter is in Girl Scouts and her troop wanted to sell Girl Scout cookies for the first time this year. In order to sell Girl Scout cookies you need an adult to be the TCPC: Troop Cookie Program Coordinate. Or as my daughter said, "We need you to be the Cookie Daddy!" I figured all this meant was they needed someone to manage an Excel spreadsheet for all the cookie sales so I agreed.

Little did I know what was in store as there is much more to it. First is all the training and webinars, background check, volunteer forms, etc. Then when it comes to finally sell cookies, there are no spreadsheets; they've got Digital Cookie online selling platform and eBudde management system. While the eBudde system and tools seem to have all the information needed on the backend, the front end is very confusing for a new user. It's very confusing and cumbersome and the key information the TCPC needs to know is spread out over different pages. Seriously, if you have to have numerous training sessions to explain how everything works and people are still asking tons of questions, your system is too complicated.

So I decided to make a spreadsheet!

Introducing the Girl Scout Cooking Tracking Template:


With this spreadsheet you still have to manually input all the cookie sale information from eBudde but now all the information you need to know is shown visually on just two sheets and is easy to understand. Here's how to use the cookie tracker:

On the sales summary page, copy and paste your Girl Scouts. Then input each of their Digital Cookie sales, which are broken into four categories: 

1. Cookies to be hand delivered (from the Initial Orders page in eBudde)
2. Donated cookies for Operation Salute
3. Any cookie sales from paper order forms that need to be input manually
4. Orders that will be shipped direct from the bakery (from the Girl Orders page)

Next, you can input each Girl Scout's goal for how many packages they want to sell. These will add up at the bottom to show the overall Troop Cookie Goal. There is a donut graph to show the troop's progress towards their goal.

On the right it shows the Instant Rewards and how many packages it takes to reach. Once a girl has reached the goal, the formula automatically shows as having achieved it.



On the next sheet, we have a breakdown of how many of each type of girl scout cookie has been sold (thin mints being the most popular, obviously). As the cookie daddy and the person responsible for picking up the cookies from the cookie cupboard to distribute to the troop, the most important info is the number of cases of each type of cookie I need to pickup. 

There is another sheet in my template that explains some of the terminology, the key being the word "box" is never used. The girls sell "packages" of cookies and 12 of those packages make up a case. The cookies are never mixed up in different cases and if you only sell one package of LemonUps, you have to pickup an entire case of LemonUps.


The Girl Scout Cooking Tracking Spreadsheet shows you exactly how many cases of each cookie you need and how many unsold packages in each case. The unsold cookies from the initial order can be used to sell in-person during the booth phase.


I added a sheet you can use as a template for booth signups.

Download the Girl Scout Cookie Tracking Spreadsheet Template here.








Sunday, January 22, 2023

Elevate Your Sports Betting Game with Our Free Excel Tracking Tool

Sports gambling just became legal here in Ohio and we've been flooded with sign-up offers. Since just about every sportsbook will give you free bonus bets (around $200) for a small ($5 or $10) deposit, I decided to dabble a little bit into sports betting to see what all the fuss is about. I signed up for three different sportsbook sites and quickly realized I needed a way to organize and track all my bets.


Naturally, I decided to make an Excel template to track which bets I'd made, track my earnings, and make sure I was still making a profit. First, I created a Lists sheet for all my drop down lists including which sportsbook, which sport, result, and so on. Personally, so far I've only stuck to football because that's what I follow the most and already have some interest and knowledge in it.


The Bet Tracker sheet is used to track every individual bet including the odds, wager amount, and formulas to determine the potential winnings and the actual result.

bet tracker sheet

When you bet with your own money, if you win the bet you get the winnings plus your original bet back. But when you use Bonus money to place your bet, that "fake" money is not added to the winnings. I had to account for this in my Potential Winnings column formula.

If your own money then: Winnings = ((Odds/100)*Wager)+Original Wager

If bonus money then: Winnings = (Odds/100)*Wager)

=IF(E2="My$",((G2/100)*F2)+F2,((G2/100)*F2))

If you get lucky and win a bet, you'll be able to withdraw the money into your own bank or Paypal account. There's a summary sheet to track exactly how much money you've put in versus what has come out. The most important stat to me is my running total, and making sure it is well in the positive otherwise it's time to quit. 


How have I done? In the past two weeks, I placed 33 bets and won 8 of them. I've only had to input $27 of my own dollars, while I've gotten to bet $650 bonus bucks. I'm not huge into taking risks, so instead of betting on crazy parleys with larger payouts, I've bet on safer, more likely outcomes but with smaller rewards. What do I plan to do with my winnings? Probably invest in an AI company since they're changing the game.

In all my years of making sports related Excel spreadsheet templates, I've never really gambled on sports. I'm not sure I'll keep gambling once my free funds run out, but it is a fun experiment while it lasts. Like playing fantasy football or Super Bowl Squares, it gives you an extra incentive for watching the game. Hey, speaking of Super Bowl Squares, I've got a new version coming out this weekend and I can't wait to hear your thoughts on it...

.Download Sports Bet Tracker.xlsx file here

Sunday, January 8, 2023

Using OpenAI's ChatGPT to Update My Year in Pixels Excel Template

I've been seeing more and more videos on TikTok about this mysterious new artificial intelligence program called ChatGPT. People are saying it will eventually replace Google search. But what really got my attention was a demonstration of ChatGPT writing VBA macros for Microsoft Excel. Now I knew I had to try it for myself. 

I made a Year in Pixels Excel template to track my daily mood back in 2018 but haven't updated it lately. Since it's the start of a new year, I recently received some new comments and questions about how to use and modify the spreadsheet so I figured now would be a great time to update it and add a few new features. Then I had an idea - why don't I use this opportunity to update my mood tracking Excel template to try out ChatGPT? Let's give it a go!


How to have cell fill color conditional formatting change based on the color of another cell?

The request from a user that got me thinking was "how to easily change the colors in my year in pixels sheet?" An experienced Excel user could probably ascertain the colors are applied by conditional formatting formula rules. However, for users who are not Excel savvy, it's not very obvious and there should be an easier way to change the colors. As far as I know, there is none, or at least no easy way in my current version of Excel, to have the fill color in the conditional formatting reference another cell's color. So instead, I will have a macro update the conditional formatting rules at the click of a button. Let's jump over to ChatGPT.

How does ChatGPT work?

Here's the answer after asking it directly: 

GPT (Generative Pre-trained Transformer) is a type of language model developed by OpenAI that uses a transformer neural network architecture to generate text. GPT is trained on a large dataset of text and uses this training to generate new text that is similar in style and content to the training data.

ChatGPT is a variant of GPT that has been fine-tuned on a specific task, such as having conversations with humans. To fine-tune GPT for this task, ChatGPT is trained on a large dataset of conversation data and learns to predict the next word in a conversation based on the words that came before it.

When you input a message to ChatGPT, it processes the message and uses its knowledge of language and conversation patterns to generate a response. It does this by predicting the next word in the conversation based on the input it has received and the context of the conversation so far. The output of ChatGPT is then a response that is generated based on this prediction.

One thing to keep in mind right off the bat: ChatGPT is not always right. It says it right there on the main page under limitations: may occasionally generate incorrect information; may occasionally produce harmful instructions.
For example, I asked "list the ten tallest roller coasters in the world" which should be fairly easy and instead it produces a list that is incorrect and doesn't even make sense.


Not a great start but let's see how it does creating a macro from scratch.

Creating Custom VBA Macros Automatically with ChatGPT

I wasn't sure how specific I needed to be so I decided to err on the side of caution, plus I thought the more detailed I am the less modification I'll probably need to do later. Now I ask ChatGPT: "create a vba macro to make a new conditional formatting rule where range is C4 to N34, if cell value = 5 then change the fill color to the same color as in cell P12." Then it began typing and my jaw dropped.

I copied and pasted the code into Excel VBA editor and it worked! One thing I forgot is this macro will just add new rules applied to the same range. I need to delete all the existing formatting rules before adding new ones, so I ask ChapGPT:


I added the above code to the earlier response and linked it to a newly added button on my sheet. Now a user can change the fill color of a cell, click the button, and the fill colors update automatically to match.

If you want to see all this play out in real time, watch the video I recorded below:

Thoughts on the Future of ChatGPT

It's awesome that it doesn't just spit out the code, but it also suggests how you might need to modify it AND tells you how to run the macro as well. Even though I've only asked it to make simple macros, I already see how this program could save a lot of time.

I'm not done experimenting but so far ChatGPT seems like a much better option over Recoding macros or Google searches that might take you a few tries to find exactly what you're looking for. Especially when you can get custom code on the fly. On one hand, I feel a little obsolete, but on the other I also don't think ChatGPT will completely be replacing programmers just yet as you can see I still had to understand the code and modify it to fit my exact needs.


Download my Year in Pixels template for free here and try it for yourself. Open the macro editor to view the final codes written by ChatGPT.

Tuesday, June 21, 2022

How to change relative hyperlink to exact link in Excel

You may have used the HYPERLINK function in Excel before but what you may not have released is your links can be either relative or absolute (or sometimes called exact or specific). What does this even mean? And how do you change from relative to exact?

Monday, March 28, 2022

Free Meeting Scheduling Excel Template

How often do you ask friends, family, or coworkers which day is the best to get together? Whether it’s a meeting, party, trip, or some other occasion I find myself in these situations all the time. There are several apps and online calendars available to help you coordinate which day works for everyone involved. I used to use a site called Doodle all the time.  The problem with these services is they are not always free, they’re constantly changing and you have to keep relearning how to use them, you have to make an online account, and so on. So I did what I always do – I decided to make an Excel template to determine which day works best for meetings and events!

I used a lot of the same concepts and macro code from my Super Bowl Squares spreadsheet. When you first open the spreadsheet you are greeted by a simple, clean setup page. Here you’ll manually input the number of participants, meeting subject and description.

Next, you’ll enter the start and end dates of the days you want the participants to choose from. It’s very important that these two cells ONLY contain dates. To restrict a user to only being able to enter a date in a cell, go to Data > Data Validation. Under Allow select Date. Be sure to enter a custom error message so if a user makes a mistake they understand what needs to be entered.

When the user clicks Generate Schedule the Schedule sheet is unhidden. The schedule can handle up to 100 participants and up to 365 days. However, you probably won’t need all that so the macro will automatically hide all the rows and columns not needed to make it easy for the user to input their information.


A lot of good Excel tips can be gleaned from examining the event timing spreadsheet. Here's a quick summary of what can be learned by dissecting this free Excel template:
  • How to add and use Option buttons
  • How to use data validation to restrict entry in a cell to a date
  • How to use data validation to restrict entry in a cell to an email address
  • How to get the day of the week from a date
  • How to use command buttons and assign specific macros to them
  • How to send emails from Excel with hyperlinks
  • How to use a formula to show only weekends in Excel
  • How to use conditional formatting to change cell color based on cell value
  • How to hide command buttons by macro
Download the Meeting Scheduler Template here.

Watch How to Coordinate Meetings with Excel

If you want to see how this spreadsheet works and some tips like how to limit a cell where a user can only input a date then watch the video below:


Try it out and let me know if you think it’s a legitimate replacement for Doodle, Calendly or whatever meeting scheduling apps you currently use. 

Thursday, January 6, 2022

How to Add an Excel Shape to Outlook Mail by VBA

Two spreadsheets I am most proud of are my Super Bowl SquaresGame Generator and my College Football Bowl Prediction Pool Manager (Bowl Pick’em Game). I’ve put a lot of time and features into these free templates. However, I still get many requests to add even more features. One of the most asked questions is “how can I share the leaderboard results when all the players aren’t connected to the same network?” I would normally respond with how I do it: “I take a screenshot of the scoreboard and manually email it to the players.” Then it dawned on me – why not automate this process to make it easy for everyone to use? Why not automatically add a picture of the Excel sheet into an email?

There are two methods I can think of off the top of my head for attaching an image into an email with a macro, and here are the pros and cons of each:

  1. The picture is saved on your PC (or needs to be saved by the macro before inserting into the email)  – but either way you have to know the location of the file.
  2. Copy and paste an image already in your spreadsheet into an email. Does not require saving the image. But you must know the shape name so the macro can find it.

For today’s tutorial, I am going to show you how to use the #2 method. 

A thread on method #1 can be found here: https://stackoverflow.com/questions/44869790/embed-picture-in-outlook-mail-body-excel-vba

You can read along or scroll down to watch the video below. Again, for this method to insert an image from a spreadsheet into an email, the image must already be created and named manually so the macro knows what image within the sheet to use.

Name the Shape or Image You Want to Copy and Paste From Excel into Email

First, I need to have a linked image in my spreadsheet that will be copied to the email. Highlight the area (the cells) that you want to have an image of, in my example the scoreboard of my Super Bowl Squares sheet. Next, I created a new sheet within my workbook where I will collect the emails of all the players. I right click, paste special, linked picture. Select the image. Under page layout go to Selection Pane. Rename the picture “Preview1” or some other descriptive name. This is what the macro will use to identify which picture to attach to the email.

I also want to allow the user the option to include a hyperlink to the Excel workbook in the email or not. To do this, I create a checkbox in Excel by going to the developer tab, insert, ActiveX controls, Check Box.

 

How to Add an Excel Shape to Outlook Mail by VBA

Attach Image to Email Excel Macro Code

Now it’s time to write the VBA macro that will automatically send an email to all the players with a picture of the latest scoreboard – all at the click of a button!

I’ve previously shared how to send an email from an Excel sheet but this is my first time attaching an image. Below is the full code with my comments explaining what is happening along the way.

Sub SendEmailUpdate()

'Optimize Macro Speed

  Application.ScreenUpdating = False

  Application.EnableEvents = False

  Application.Calculation = xlCalculationManual

 

'define the workbook, location, and name

Dim Wb1 As Workbook

Set Wb1 = ThisWorkbook

 

Dim OwnerName As String

OwnerName = Application.UserName

 

Dim FileLoc As String

FileLoc = Wb1.FullName

 

Dim WorkbookName As String

WorkbookName = Wb1.Name

 

'SendEmailTo will count the number of people who the email will be sent to

Dim SendEmailTo As Integer

SendEmailTo = 0

 

'we will store all the email addresses in one long string then insert them into the TO line of the email later

Dim ToPerson As String

ToPerson = ""

 

'loop through all players in column A of the Send Scoreboard sheet (up to 100 players max)

Dim x As Integer

For x = 2 To 101

 

    ' get the emails to fill in the TO line

    If Not IsEmpty(Wb1.Worksheets("Send Scoreboard").Range("A" & x).Value) Then

    ToPerson = Wb1.Worksheets("Send Scoreboard").Range("A" & x) & "; " & ToPerson

    SendEmailTo = SendEmailTo + 1

    Else

    'MsgBox "email is blank"

    'NoSEnd = NoSEnd + 1

    End If

   

    ' get the emails to fill in the CC line

    'If Not IsEmpty(WB3.Worksheets(1).Range(CCCol & PICRow).Value) Then

    'CCPerson = WB3.Worksheets(1).Range("D" & PICRow) & "; " & CCPerson

    'CCEmail = CCEmail + 1

    'Else

    'End If

 

Next

 

MsgBox "Email will be sent to " & SendEmailTo & " recipients."

 

how to send email from excel

'get the named Image to attach to the email and copy it

Set oPreview = Wb1.Worksheets("Send Scoreboard").Shapes("Preview1")

oPreview.CopyPicture ' oPreview is now in Clipboard

 

'launch Outlook

    Dim xOutApp As Object

    Dim xOutMail As Object

    Dim xMailBody As String

  

    On Error Resume Next

   

    Set xOutApp = CreateObject("Outlook.Application")

    Set xOutMail = xOutApp.CreateItem(0)

  

'for html email

 

If Wb1.Worksheets("Send Scoreboard").CheckBox1.Value = True Then

    'include the link to the spreadsheet

    xMailBody = "Hello everyone! <br><br>" & "The SuperBowl Squares scoreboard has been updated. You can access the sheet by clicking the link below. <br><br>" & _

    "Link: <br><br>" & "<a href=" & Chr(34) & FileLoc & Chr(34) & " > " & WorkbookName & " </a> " & "<br><br>" & _

    "Thanks for playing," & "<br><br>" & OwnerName

Else

    'false, no link

    xMailBody = "Hello everyone! <br><br>" & "The SuperBowl Squares scoreboard has been updated. Please see the below image: <br><br>" & _

    "Thanks for playing," & "<br><br>" & OwnerName

End If

 

 

    On Error Resume Next

   

    With xOutMail

        .To = ToPerson

        '.CC = CCPerson

        .BCC = ""

        .Subject = WorkbookName

        '.Body = xMailBody

        .HTMLBody = xMailBody

        .Display   'or use .Send

 Quick Note: To use the clipboard to copy and paste the picture into email, you need an Outlook mail editor which can deal with the clipboard. Here I use WordEditor for example. The WordEditor property of the Inspector class returns an instance of the Document class from the Word object model which represents the Body of your email: https://docs.microsoft.com/en-us/previous-versions/office/developer/office-2007/dd492012(v=office.12)?redirectedfrom=MSD

       

        Set oInspector = .GetInspector

        Set oWdDoc = oInspector.WordEditor

   

        Set oWdContent = oWdDoc.Content

        Set oWdRng = oWdDoc.Paragraphs(1).Range

        'oWdRng.InsertBefore "This is a test"

        oWdRng.InsertParagraphAfter

        oWdRng.InsertParagraphAfter

 

        Set oWdRng = oWdDoc.Paragraphs(3).Range

        oWdRng.Paste ' paste from oPreview Clipboard

 

        olFormatHTML = 2

        .BodyFormat = olFormatHTML ' change to HTML

       

    End With

   

    On Error GoTo 0

   

    Set xOutMail = Nothing

    Set xOutApp = Nothing

'---------------------------------------------------------------

ResetSettings:

  'Reset Macro Optimization Settings

    Application.EnableEvents = True

    Application.Calculation = xlCalculationAutomatic

    Application.ScreenUpdating = True

End Sub

Monday, December 6, 2021

2021 College Football Bowl Prediction Pool

The college football conference championships were played this past weekend which means the 2021 NCAA college football bowl season is here again! Therefore, it’s time to make your picks and predictions about who you think will win each bowl game. One of the best times of the holiday season (other than giving and receiving gifts) is being able to talk trash to your relatives about their terrible bowl picks. This year has the added bonus of not just single bowl games but the eighth year of a four team playoff to determine the national champion.




Features for this year's bowl prediction pool over the previous college football bowl pool manager spreadsheets include the following:

  • Easy method to make each bowl game worth a different point value, so the national championship game and semi-finals can be worth more points, or however you want to customize it.

  • Updated leaderboard tab with new stats

  • Separate entry sheet to pass out to participants or co-workers that can be imported automatically by a built-in macro

  • Complete NCAA college football bowl schedule with game times and TV stations

  • New stat sheet to track each conference's record during bowl season. Graph shows total conference teams and total conference wins

bowl pick em excel sheet download


The bowl prediction sheets include the football helmet designs for every team (taken from the 2017 college football helmet schedule spreadsheet), their win-loss record, and the logo for all bowl games. I added the helmets so those players who aren't big college football fans can pick a winner based on their favorite helmet design!

Download the CFP Pool Manager and Single Entry Form here

I'm working on a new version where you could do confidence points that you can test out now and give me feedback.



Download the 2021 CFP Bowl Prediction Pool Manager.xlsm file here

Please let me know if you have any questions, comments, find any bugs, or have any suggestions for improvement. I love that people are using this Bowl Prediction Game to help raise money for charity, that's so awesome to hear! What team are you rooting for?


Thursday, November 18, 2021

Gift Guide for Excel Users 2021

 The 2021 holiday season is officially upon us here in the United States which means it’s time for my annual gift giving guide. I used to panic every year whenever my spouse, parents, and siblings asked me what I wanted for Christmas. I needed to give them an idea otherwise I’d end up with an ugly sweater or some random gadget I would never use.

So to help alleviate some of my stress I started compiling my own holiday gift guide. It’s kind of like the big toy catalog you used to get as a kid, only this is for adults. I’ve made a list of items I think would be very useful or exciting for your fellow Excel users, sorted by different categories (and yes, this post does contain Amazon affiliate links). Some of these items I already use on a daily basis and others are things that are on my own personal wish list. It's my biggest and best gift guide yet! Enjoy!

Monday, March 15, 2021

Excel Tips from the Best 2021 March Madness Brackets

After a year hiatus it’s finally here, the college basketball March Madness brackets are back! Last year, I made a NFL Draft Game spreadsheet for the first time to try to compensate for the loss of the basketball brackets but it just wasn’t the same (but I did still update it for 2021). This year, the 2021 NCAA men's basketball tournament will be unlike any March Madness that has come before. All games will be played in Indiana, with most in Indianapolis. The schedule has also been change. The First Four would typically be played on Tuesday and Wednesday night with the first round being played on Thursday and Friday. 

Here's the 2021 March Madness schedule:

  • First Four — 4 p.m. start on Thursday, March 18
  • First round — 12 p.m. start on Friday, March 19, and Saturday, March 20
  • Second round — 12 p.m. start on Sunday, March 21, and Monday, March 22
  • Sweet 16 — 2 p.m. start on Saturday, March 27, and 1 p.m. start on Sunday, March 28
  • Elite Eight — 7 p.m. start on Monday, March 29, and 6 p.m. start on Tuesday, March 30
  • Final Four — 5 p.m. start on Saturday, April 3
  • NCAA championship game — 9 p.m. Monday, April 5

Once again, I will be using the best March Madness brackets in Excel, created by David Tyler (and I will continue to use his until he decides to no longer update them). They’re very polished and easy to use. There are only 68 teams in the field but the spreadsheet is already setup to handle up to 128 teams, if they expand in the future. There are two sheets: the bracket and the pool manager. Instructions are included but its very intuitive. 

march madness 2021 bracket spreadsheet template


The First 5 Things I Do When Examining Someone Else's Spreadsheet

As I’ve said countless times before, you can learn a lot by looking at templates made by others. Here are 5 things I do when examining a new spreadsheet:

1. Unhide hidden sheets, columns, and rows: When you make a template others are going to be using, you want to make it look nice and clean and hide anything that could cause confusion to a first time user, which leads to hiding rows, columns, or even entire sheets in a workbook. So, the first thing I do when examining someone else’s template is look for the hidden data. Right click on the sheets tab and click “unhide”. I unhide all the hidden sheets if there are any to see what data is present. Look for any hidden columns or rows as well by seeing if any letters or numbers are skipped.



2. Understand the NamedRanges: Go To Formulas > Name Manager and examine what the named ranges are, what sheets and cells they refer to. Hopefully they're all named well, like in David's brackets.



3. Look at conditional formatting rules: On the Home tab, go to Conditional Formatting, click Manage Rules, then Show formatting rules for This Worksheet to view them all.



4. Look through the formulas: On the Formulas tab, click “show Formulas” to show if they were manually typed in or if there is a formula calculating the values



5. Look through the macros: Hopefully, the person writing the code left lots of good comments so it’s easier to follow along with what each piece of code does



Watch me quickly walk through David's 2021 March Madness brackets going through the five points listed above:


Thursday, February 4, 2021

COVID-19 Vaccine Distribution Tracking Template

Not sure if this is helpful to anyone but I made a COVID-19 Vaccine Distribution Tracking document in Excel. It’s hard to make a spreadsheet that you’re probably not going to use personally yourself. But I tried to envision being in management of a company or nursing home or school that needed to:

 (1) prioritize which employees or residents or teachers should get the vaccine first and

 (2) track which people have actually gotten the vaccine and when.

 

covid-19 vaccination tracking spreadsheet

What Order to Distribute the Vaccine

The first item I tackled was how do you decide in what order to give out the vaccine. Knowing that supplies are limited, who gets the first dose?

I use a scoring system to decide the priority order: the highest score is first in line to get their shots.

 Here’s how the score is calculated:

  1. Age: the score starts with the person’s age. 30 years old = 30 points. The older population automatically has a higher score.
  2. Age multiplier: I made up a tier system based on age. Based on earlier data I’ve seen, the chance of dying from COVID if you’re 59 years or younger is only around 1% or less, but this jumps up to nearly 20% if you’re 80 or older. In my scoring system, those 60 and older get varying amounts of “bonus” points added to their score depending on what age range tier they fall into.
  3. Priority person: Yeah, you could just rank vaccination order by age and be done with it but I didn’t want age to be the only limiting factor. There are other variables that I wanted to account for. I added the ability for a person to be marked as “high priority”, maybe due to immune deficiency or because they’re a first responder, or pregnant – whatever you want it to be. This adds 11 points to their score to help bump them up in the distribution order. Again, the spreadsheet is easily customizable so you can change the bonus to whatever value fits your needs.
  4. Male or female: This might be controversial, but I added a segment to the scoring where males get a slight score increase over females. From the data I have (and please send me any new information if you think I’m wrong) males have a ~3% higher death rate from COVID than females (women are generally better at fighting off infections I’ve heard) so they get +3 point bonus while females get none. Of course, feel free to change this setting to make it what you want. Give woman 1,000 bonus points and men 0 – it’s up to you and can be easily changed in the spreadsheet.

The total score is calculated by adding up the age, the age tier multiplier, the male/female bonus, and the priority bump. The biggest factor is age, as that is the biggest factor of death rate. While getting the highest score means you’re first in line to get the vaccine, that also means you have the highest risk of dying from COVID.  I then use the RANK function in Excel to rank the individuals from highest to lowest score. There’s your priority list of who gets the vaccine first.


Vaccine Distribution Tracking

The next component, after deciding the vaccination order, is to then track if these people actually got the vaccine. Complicating matters, there are (right now) two different vaccines being distributed in the US requiring two separate doses and the time between doses is different. Each vaccine also has a minimum age requirement that is different so there is a formula to make sure the individual is old enough to get the selected vaccine. If they’re not eligible, meaning you’re too young, your score automatically goes to 0 and I use condition formatting to turn the cells black to show the individual shouldn’t be scheduled to get a shot. Once you get the first dose, enter the date and the spreadsheet will tell you when the earliest is you can get the second dose based on which vaccine you got. Finally, you can quickly see how many of your employees or residents have received the first or second doses of the vaccine.

 Download the spreadsheet here: https://gumroad.com/l/covid-tracker

I’ve been wanting to put my Excel powers to good use rather than just making Super Bowl squares or football related spreadsheets. Not sure the legality of it but if I was in charge of a company with employees working from home I would want to know when it is safe to bring that back into the office. Try it out and let me know what you think!

Tuesday, July 7, 2020

Rename Excel Workbook Based on Number of Files Macro


Let’s say you have a task where you want to include a control number in an Excel sheet and in the name of the file which is based on the total number of Excel files contained within a folder. If you’re not familiar with writing VBA macros for Excel, see my getting started guide here.

For this example, there are currently three Excel files saved in a folder with these names:

Doc-Control-01
Doc-Control-02
Doc-Control-03

We want to save our latest document using the name Doc-Control-04, but how does Excel know to use “04” at the end?

As with any complicated task, the first thing I do is break it down into smaller, more manageable steps.

  1. The user selects the folder where to save the Excel documents
  2. The macro saves the open workbook into the folder with a “ZZZ” placeholder in the filename
  3. The macro counts the number of Excel files in the folder.
  4. The macro adds the control number based on this count into the spreadsheet
  5. The macro saves a copy of the workbook in the same folder but replaces the placeholder  “ZZZ” in the file name with the control number count
  6. The macro deletes the first copy the Excel document

Here’s a rundown of the VBA code:

Sub Generate_Documents()

'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual
 
Dim Wb2 As Workbook
Set Wb2 = ThisWorkbook
ThisWorkbook.Sheets(1).Select
Wb2.Activate

'---The control number will be in cell G7. For now we input placeholder “ZZZ”
Wb2.ActiveSheet.Range("G7").Value = “ZZZ”

'----save the Excel document VBA----
'dialog box to save the spreadsheet
Dim InitialName As String
Dim fileSaveName As Variant
InitialName = “Control Number: “ & Wb2.ActiveSheet.Range("G7").Value
fileSaveName = Application.GetSaveAsFilename(InitialFileName:=InitialName, fileFilter:="Excel Files (*.xlsx), *.xlsx")

If fileSaveName = False Then
        MsgBox "File not saved. You must save the file!"
        Exit Sub
       ‘exit the program so we don’t delete the template file
        Else
        Wb2.SaveAs Filename:=fileSaveName
        End If
       
‘now the macro knows what folder to look in to count the files

'Next, create the Control number by counting excel files in the folder and rename
'count existing excel files in the save folder
'First, get the location WB2 was just saved in
Dim WB2Path As String
WB2Path = Wb2.Path

Dim FileCount As Integer
Dim FolderPath2 As String, path2 As String

FolderPath2 = Wb2.Path

path2 = FolderPath2 & "\*.xls*"

    Filename = Dir(path2)
FileCount = 0
    Do While Filename <> ""
       FileCount = FileCount + 1
        Filename = Dir()
    Loop
    'MsgBox FileCount
   
     
    '---control number. If less than 10 add a 0 to display 01, 02, etc.
If FileCount < 10 Then
Wb2.ActiveSheet.Range("G7").Value = "0" & FileCount
Else
Wb2.ActiveSheet.Range("G7").Value =  FileCount
End If

Dim OldName As String, newName As String
OldName = Wb2.FullName

‘use the replace function to automatically replace placeholder “ZZZ” with the document control number
newName = Replace(OldName, "ZZZ", Right(Wb2.ActiveSheet.Range("G7").Value, 2))

‘save a copy of the sheet with the control number in the file name
Wb2.SaveAs Filename:=newname

‘delete the old workbook
Kill OldName

'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
End Sub

Let me know in the comments below if you have any questions how to rename a workbook based on the number of files in a folder.