Showing posts with label VBA. Show all posts
Showing posts with label VBA. Show all posts

Sunday, December 8, 2024

2024 College Football Bowl Pick'em and Playoff Bracket

It's the most wonderful time of the year - college football bowl season! The college football conference championships were played this past weekend which means the 2024 NCAA college football bowl season is here again. 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 is being able to talk trash to your relatives about their terrible bowl picks.

This year has the added bonus of the new, expanded college football playoff - growing from four to twelve teams. As such, I've included a college football playoff bracket within this Excel file. There is the option to play just the bowls, just the playoff bracket, or both! If you've used my Super Bowl Squares template, you'll be familiar with how it works - there is a setup screen where you pick your options then click a button and the spreadsheet adjusts to how you want to play.

2024 2025 ncaa college football bowl prediction template


The bowl prediction sheets include the football helmet designs for every team (taken from my 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!

There are multiple ways to play college football bowl pick'em. What I call "regular" is every game is worth 1 point. The other way I call Confidence Picks: each player "bet" points 1 to 35 on each game based on how confident they are their choice is correct. Player with the most points wins                 Example: player bets 35 points and gets it correct = 35 points. Bets 25 points on another game, gets it wrong = 0 points awarded.

For the college football playoff bracket, the pool manager can decide if each game is worth the same amount (1 point) or if each round the points increase: round 1 = 1 point, round 2 = 2 points, etc.


2024 College Football Bowl TRIVIA

  • First year of 12 team playoff bracket
  • 35 bowl games with 70 teams
  • No teams with a losing record
  • Best record: Oregon 13-0
  • There are only 2 teams left in the Pac-12
  • The Alamo Bowl features two teams from the same conference (Big 12 vs Big 12)
  • 18 teams with 6-6 record (21 teams last year)
  • 21 teams with double digit wins (23 in 2023,  16 in 2022, 23 in 2021, in 2020 there were 5, 22 in 2019)
  • One loss teams: Army, Indiana, Notre Dame, Boise State
  • Lopsided matchups (in terms of records): Memphis 10-2 vs WMU 6-6, UNLV 10-3 vs Cal (6-6)
college football bowl teams conference breakdown

Download the CFP Pool Manager and Single Entry Form here


Have fun! As always, I welcome any feedback or ideas for improvement.

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...

Wednesday, June 26, 2024

Facebook Marketplace Sales Tracking Template Updated

 I've sold 227 items on Facebook marketplace. Here's what I've learned:

The day of the week when I make the most sales on Facebook marketplace is Wednesday, followed by Tuesday and Sunday. The worst day of the week for sales is Friday, followed by Saturday and Monday.


I've been selling on Facebook Marketplace since July 2020 and by far the best months for most sales have been November and December, with February and April being the worst.


56% of my sales have been picked up by the customer in-person, while 44% paid for shipping on top of the cost of the item.



The average length of time to sell an item on Facebook Marketplace is 112 days. The longest sale took 828 days (or 2.2 years)!

54% of customers will try to barter or negotiate a lower price than what you have initially listed the item for. On average, customers will try to reduce your price by 20%, so you should account for this when listing your items.


Example: if you want to make $50 off a product, list it for $60.

Do you want to track this data for yourself? 

Download my free Facebook Marketplace Sales Tracking spreadsheet here.

I recently updated my template. You can now use this one spreadsheet to track sales for various marketplaces, such as Mercari, Ebay, Craiglist, Whatnot, etc. Previously you had to manually drag down formulas and added new listings at the bottom. Now you simply click a button and a new row is automatically added via VBA macro at the top for you to add the listing info. All the data is in the Summary sheet and update automatically via Excel formulas.

Have you ever sold anything on Facebook Marketplace and if so do you track your sales? Have any tips for me or questions? Let me know via comment or email!

Thursday, May 16, 2024

NFL Helmet Schedule 2024 Spreadsheet

 The 2024 NFL schedule was released yesterday and since I used my Excel skills to automate the creation of this spreadsheet I was able to create the NFL Helmet Schedule in less than a minute! All 32 teams, all 18 weeks of the season (now 17 games plus one bye week), all in one spreadsheet. But instead of looking like this boring mess:


You can see all 544 helmets!

NFL Helmet Schedule 2024 Spreadsheet


Watch the video below to see just how easy it is to update the NFL helmet schedule spreadsheet since it has been automated:


As you can see, the NFL helmet schedule is printable too. You can save the spreadsheet as a PDF file or print it out and pin it up in your cubicle at work. If you do, please email or tweet me a picture of it hanging up - I'd love to see it!

Please note, an email is required to download it. I do this so you will be automatically updated you if changes or additions are made and will update you when the next year’s schedule is ready. I do not use your email for anything else.

As always, I welcome any comments or suggestions about how to fix or improve the sheet! How can I improve this football spreadsheet into something you’ll use all the time during pro-football season? What future features would you like to see?

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.

Sunday, January 28, 2024

Super Bowl Squares 2024 - The BEST Excel Templates

It's finally time to play Super Bowl Squares! As the biggest sporting event of the year approaches, hardcore football and casual fans alike gear up for an unforgettable Super Bowl experience. To add an extra layer of excitement to your game day festivities, I'm here to introduce you to the magic of Super Bowl Squares and simplify the process with my specially crafted and powerful Excel template. Whether you're a seasoned veteran or a newcomer to this classic game of chance, my template is designed to make organizing and tracking your Super Bowl Squares pool a breeze. Let's get to it!

I’ve been making Super Bowl Squares templates available for you to download since 2012 and the latest versions are the most versatile yet. There are two templates to choose from, I'll explain the pros and cons of each.

2024 Super Bowl Squares - 54 Ways to Play

Released in 2021, this is the more "classic" and straightforward way to play. When you first open the sheet, it has a nice clean look with only one sheet visible. You select the options for how you want to play, click Generate Squares, and it sets up the sheet exactly for the version you want to play. 

excel file for superbowl squares template


The way it works is all the scoring systems are already built into the sheet. If you go to the Squares or the Manager sheet you will find many hidden rows or columns. The Generate Squares macro simply hides or unhides the data based on the user’s selections.


Download 2024 Super Bowl Squares here


Super Bowl LVIII Squares Unlimited

54 ways to play apparently wasn't enough as I still received numerous requests for customizations and more features. This lead to the creation of a new approach to the template: Super Bowl Squares Unlimited. The main difference in how it works is there are no pre-built scoring systems. Instead, they are built on the fly by macros based on the user's input; therefore there are an infinite number of ways to play.


This sheet offers the most flexibility but might take some getting used to. At first it may be a little difficult to understand how the scoring works, so I recommend you watch this video:


Friday, May 12, 2023

2023 NFL Helmet Schedule Spreadsheet

The 2023 NFL schedule was released yesterday and since I used my Excel skills to automate the creation of this spreadsheet I was able to create the NFL Helmet Schedule in less than a minute! All 32 teams, all 18 weeks of the season (now 17 games plus one bye week), all in one spreadsheet:


A job that used to take hour by moving helmets manually is now so easy to do. Yes, that's why I love the power of macros and automation. I wrote the macro myself but nowadays you could probably just ask ChatGPT to write the macro for you.

On previous versions of the sheet I divided out the two conferences on separate sheets: NFC and AFC. This year, I’ve put all the teams into one sheet. However, there is a new filter option where you can filter by NFC or AFC or even by division: AFC North, AFC South, etc.

Download the 2023 NFL Helmet Schedule Spreadsheet here


Watch the video below to see how the filter works. I also so a tip in Excel how to select multiple objects at once with the mouse. And I walk through the populate helmets macro code as well. Lots of good stuff here!

As you can see, the NFL helmet schedule is printable too. You can save the spreadsheet as a PDF file or print it out and pin it up in your cubicle at work. If you do, please email or tweet me a picture of it hanging up - I'd love to see it!

Please note, an email is required to download it. I do this so you will be automatically updated you if changes or additions are made and will update you when the next year’s schedule is ready. I do not use your email for anything else.

As always, I welcome any comments or suggestions about how to fix or improve the sheet! How can I improve this football spreadsheet into something you’ll use all the time during pro-football season? What future features would you like to see?

Sunday, January 29, 2023

Super Bowl Squares 2023 - Unlimited Ways to Play

Since 54 ways to play still wasn't enough, I've created a new version of my Super Bowl Squares template that should allow nearly limitless ways to play. I'm going to show you how to use it and what make it awesome. But first, let's take a quick look back at the evolution of my football grid game template.

I’ve been making Super Bowl Squares templates available for you to download for over 10 years now. The first version in 2012 was very plain and simple and was basically just meant to be printed.


I started adding more features and automation in 2014, beginning with a button you would click that runs a macro to generate the random numbers. 

The problem I soon discovered is there are countless ways to play Super Bowl Squares. Initially, I tried to account for different ways to play by having multiple sheets within the workbook. But this got very messy very quickly. A new user would open the template and could be very confused by all the sheets. I wanted a better solution.

In 2021, I released a new version that featured 54 different ways to play Super Bowl Squares all contained within one easy to use spreadsheet. When you first open the sheet, it has a nice clean look with only one sheet visible. You select the options for how you want to play, click Generate Squares, and it sets up the sheet exactly for the version you want to play.


The way it works is all the scoring systems are already built into the sheet. If you go to the Squares or the Manager sheet you will find many hidden rows or columns. The Generate Squares macro simply hides or unhides the data based on the user’s selections.

54 ways to play is a lot – but it is still not enough. Over the years I continued to receive countless requests for different ways to play. I don’t have time to make very specific sheets for each individual request – I needed a solution to account for unlimited ways to play. 

That’s when I had the idea for Super Bowl Squares Unlimited. The main difference in how it works is there are no pre-built scoring systems. Instead, they are built on the fly by macros. 


If you’re using iOS or cannot enable macros you will not be able to use this sheet, sorry. The is a simple printable PDF in the download and here is a Google sheet.

The first thing you’ll want to do is go to the Manager sheet and complete columns B and C by inputting all the player names and using the drop down to select how many squares for each. You can type the names manually into each square but you would also have to list the names on the Manager sheet and make sure they match (no typos). 

Back to the Squares sheet, the buttons in the Grid Tools box are pretty self explanatory. On the squares sheet, click the Random Names button to populate the grid with the player names in random positions. Click Randomize Numbers to generate the list of random numbers. Similar to previous sheet.

The main difference that gives this sheet more flexibility is the score boards are not built in, they are generated when the user clicks the Generate Scoreboard button every time there is a scoring event. Meaning, the settings can be changed. Let’s look at some examples.


So that’s how you use the Super Bowl Squares Unlimited spreadsheet template. I’m excited to hear your thoughts. Is it better than the previous sheet? This is brand new and hasn’t been tested too much so there could be some bugs. But I’d love to know your thoughts on which sheet you will use and why so leave me a comment or email. Thanks for watching and have fun playing Super Bowl Squares!







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.

Sunday, June 12, 2022

2022 NFL Helmet Schedule Spreadsheet

 As I explained last year, I finally automated this spreadsheet so I was able to create the 2022 NFL Helmet Schedule in less than a minute! All 32 teams, all 18 weeks of the season (now 17 games plus one bye week), all in one spreadsheet:


A job that used to take hour by moving helmets manually is now so easy to do. Yes, that's why I love the power of macros and automation. See how fast the sheet can be created by watching this clip:


On previous versions of the sheet I divided out the two conferences on separate sheets: NFC and AFC. This year, I’ve put all the teams into one sheet. However, there is a new filter option where you can filter by NFC or AFC or even by division: AFC North, AFC South, etc.

Download the 2022 NFL Helmet Schedule Spreadsheet here


Watch the video below to see how the filter works. I also so a tip in Excel how to select multiple objects at once with the mouse. And I walk through the populate helmets macro code as well. Lots of good stuff here!



As you can see, the NFL helmet schedule is printable too. You can save the spreadsheet as a PDF file or print it out and pin it up in your cubicle at work. If you do, please email or tweet me a picture of it hanging up - I'd love to see it!

Please note, an email is required to download it. I do this so you will be automatically updated you if changes or additions are made and will update you when the next year’s schedule is ready. I do not use your email for anything else.

As always, I welcome any comments or suggestions about how to fix or improve the sheet! How can I improve this football spreadsheet into something you’ll use all the time during pro-football season? What future features would you like to see?

PS. I will not be rooting for the dumpster fire known as the Cleveland Browns this season so if any fanbases want to recruit, now's your chance to pitch me on your favorite team!

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

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!