Showing posts with label Tutorial. Show all posts
Showing posts with label Tutorial. 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 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

Sunday, April 5, 2020

2020 NFL Draft Game in Excel

It's been a couple of weeks without sports now and man has it been hard. I've especially missed March Madness and filling out brackets.

I've been trying to think of ways to make up for the loss of sports. The 2020 NFL Draft is one of the few sports-related things still scheduled to go on (for now). My friend Isaic gave me the idea to make a NFL Draft Game in Excel.

nfl fantasy draft template in excel 2020


Inside this template I've listed the top 100 draft prospects according to ESPN. Each player (and the template is setup to handle ten players) are randomly assigned ten future NFL players by using a randomize macro. The earlier your players get drafter the better as the draft position counts for points and the lowest number of points wins!

Update 4/17/20 - new options added!

Based on some good user feedback I added the option where each player can now try to predict which team will select their players.

guess the nfl draft order game excel file


See how the Draft Game spreadsheet works in the video below:



Download the NFL Draft Game Excel Template here.

Even if you have no interest in the NFL, football, or drafts, you can still learn a bit about Excel by examining the random number generator macro, or the vlookup and sumif formulas used.

For now, the spreadsheet is setup to handle ten players. To add more, the formulas and macro will need to be modified. If enough people are interested in using this sheet, I will work on making it scalable so it can automatically adjust to the exact number of players.

Let me know if you like this game or if you have any suggestions or questions.

Sunday, January 7, 2018

Year in Pixels 2018 Mood Tracking Template

Year in Pixels is a cool idea I recently saw on Pinterest and decided I would make an Excel template for it to help save you the time of having to make your own using pencil and grid paper. Each day of an entire year is given one square or “pixel” and after every day you color in what your mood was for that day. It’s a great way to track your well-being to get a visual representation for how your year is going.

At the end of the year you’ll be able to answer the questions: How many days a year am I really happy or how many bad days do I experience in a year? Too many bad days in a row means it’s time to make a change.

During a day you may experience a wide variety of feelings. This chart doesn’t go that deep, it’s more what the culmination of everything is: was it a good day, an OK day, or a bad day?

The template is modifiable. You can change the colors if you want: I’ve decided to go with warm for happy feelings and cold for sad feelings. You can also change the number of colors/moods you want to track. I’ve gone with just five for now.

There are multiple sheets included within my template: a printable version, an Excel (electronic) version, and an example.

The printable version is for you old fashioned folks who want to print it out and color in the squares by hand with markers, crayons, or colored pencils. Feel free to hang it on the fridge or somewhere visible where you won’t forget to fill it out every day.



Personally, I prefer the Excel version because then I can do other things with it, like automatically sum up the total number of good versus bad days to know exactly what my percentages are.


See how easy it is to use the Year in Pixels template by watching the video below:



This template uses drop down lists, conditional formatting, and nested IF formulas. If you’re not sure what any of those are, I highly recommend downloading the sheet and taking a look at how it works.

Download Year in Pixels Excel Mood Tracker.xlsm

--Year in Pixels 2023 Update--

Happy New Year! I've made a few updates to the Pixel Year spreadsheet. First, I switched the format from xlsx to xlsm so I could add a macro. This way you can change the colors from the default to whatever you want at the click of a button. I also added a Yearly sheet so you can track your average and number of days for each category for each year and compare your years. See how I made the updates in the video below. Download link is the same.

 
Now you can track your mood in Excel with the Year in Pixels spreadsheet. Let me know in the comments below if you’re going to use it this year!

Saturday, June 10, 2017

How to Hide Gridlines in Excel - Three Ways

Gridlines in Excel are the faint, grey colored lines that appear around cells in a spreadsheet to distinguish them from one another. By default, the gridlines are displayed in worksheets using a color that is set by Excel. You can essentially turn off the gridlines, cover up the gridlines, or change their color in order to hide them.
There are at least three methods you can use to hide the gridlines in Excel.
1. The proper method is to go to View then uncheck the Gridlines box. You can hide gridlines on multiple sheets by selecting all the sheets first, then unchecking the box.



2. Change a cell’s fill color to white or another color. If you apply a fill color to cells on your worksheet, you won't be able to see or print the cell gridlines for those cells.

3. Change the gridline’s color to white. You can change the default Gridline color by going to File > Options > Advanced then scroll down to Display options for this worksheet.

To see how to do each one of these check out the video below.

Borders are not the same as gridlines in Excel

People often confuse borders and gridlines in Excel. Gridlines cannot be customized in the same manner that borders can. If you want to change the width or other attributes of the lines then you need to use a border. Gridlines are always applied to the whole worksheet or workbook, and can't be applied to specific cells or ranges. If you want to apply lines selectively around specific cells or ranges of cells, you should use borders instead of, or in addition to, gridlines.



Let me know if you found this Excel tip helpful!

Tuesday, February 21, 2017

How to link a textbox to a cell Excel Macro

If you’re putting together some kind of diagram in Excel, you may want to have the ability to click on a shape or textbox and have it automatically jump to another location, like a cell. I have always believed it is faster to mass produce things then manually delete what you don’t need rather than manually creating textboxes, and this is another example of that. I would run a macro to create 50 linked textboxes and then if I only use 30 I can quickly delete the left over 20.
For example, the macro creates ten Textboxes and then links them to cells A1 through A10 using an automatically created hyperlink. The two most important expressions we will be using are:
To add and position a new Textbox using VBA:
.AddTextbox(Orientation, Left, Top, Width, Height)
To add a hyperlink to a textbox using VBA:
.Add(Anchor, Address, SubAddress, ScreenTip, TextToDisplay)
How to link a shape to a cell Excel Macro

If you’re not familiar with programming VBA macros in Excel, check out my quick start guide here. Listed below is the complete code with my comments to help walk you through it:
Sub CreateTextBoxes()
Dim i, d As Integer
‘d will be used as spacing to separate the textboxes so they are not created on top of one another
d = 10
‘perform the loop 10 times and create 10 textboxes. Could change this to be more or into a user input box
For i = 1 To 10
'create textboxes in a vertical column with equal spacing using d
       ActiveSheet.Shapes.AddTextbox(msoTextOrientationHorizontal, 150, 20 + d, 35, 25).Select
   
'add formula to textboxes so the textbox displays the text in the cell
    Selection.Formula = "=$A$" & i
   
'create hyperlink from textbox to cell, assumes sheet name is Sheet1
       ActiveSheet.Shapes.Range(Array(i)).Select
    ActiveSheet.Hyperlinks.Add Anchor:=Selection.ShapeRange.Item(1), Address:="", SubAddress:="Sheet1!A" & i
   
    d = d + 30
  
Next
End Sub

How to link a shape to a cell Excel Macro Video




If you put some values in cells A1 – A10 and then run this macro, it will create 10 textboxes, and when you click on the textbox it will jump to the location of the appropriate cell.  Download this sample file here.

Wednesday, July 13, 2016

How to Write a Book Fast by Using Excel - Video Tutorial

Where most authors are writing their books in Microsoft Word, Scrivener, or Pages for Mac, I’ve actually been using Microsoft Excel to write books fast and today I’m going to show you my exact technique. You can see an example of one of my books created in Excel by checking out The 50 Most Terrifying Roller Coasters Ever Built on Amazon.com. As you can see, it has a 4.5 star rating from 14 reviews - none of which are from people I know, all real readers and customer - and has sold more than 2,000 copies. I’ve written four books using this technique and I chose this niche because I have a real passion for roller coasters and amusement parks.

Why write a book in Excel?


List type blog posts and articles are very popular these days, so my idea was to turn one of these type of list posts into a short book. This method is probably not a good idea for every type of book. You wouldn’t want to write a novel or long work of fiction in Excel. But if you're trying to relay stats or facts or have some form of repetition then this technique could help save you a lot of time. Anytime you find yourself doing something over and over or thinking to yourself "there has to be a better way" then, guess what, there probably is a better way and macros could be the answer.

How do you write a book in Excel?

Each row in my spreadsheet template starts a different page in the book. So 50 coasters equals at least 50 pages. I’ve colored coded the spreadsheet: every column in green is my initial input. Orange columns are formulas that use information from two other columns. All columns without color contain data that was entered by a virtual assistant whom I hired specifically for this job from Upwork.

Basically, I came up with the list of 50 coasters I wanted to feature in the book, then I outsourced the data collection process using Upwork. While my virtual assistant was contacting theme parks and researching data, I wrote the code to the macro that would automatically export all the data from Excel into the format in Word that I was looking for. The macro runs through a simple For..Next loop, looping through each row of the spreadsheet and exporting the data into the Word document.



After the information is exported to Word, just add your typical front and back matter, pictures, edit, and you’re done. Uploading to CreateSpace and Kindle Direct Publishing is a breeze. And you can outsource most of these tasks as well, if you have the budget for it. Or do it yourself. Most people don't realize that if you have something written, it could be on sale on Amazon.com in as little as two days. Heck, some guy got a picture of his foot to be a best seller.


Watch My Book Magically Appear


Watch the video tutorial below where I show you how to write a book fast by using Excel and see the book pages magically appear before your very eyes.


Steps to Write a Book Using Excel


Here's the basic steps I use to start writting my book with a spreadsheet:
  1. Setup Excel sheet
  2. Outsource data entry using Upwork
  3. Create macro to automatically export data to Word
  4. Run Macro
  5. Add front and back matter, pictures, etc. to book in Word document
  6. Edit and create front cover
  7. Publish on CreateSpace and KDP
  8. Market and promotion
Feel free to contact me if you'd like to know more or have questions about how the macro works to export the data from Excel into Word.

Wednesday, May 18, 2016

How to Create folders with hyperlink from Excel Macro

I've previously shared how to automatically create folders from an Excel spreadsheet by using a macro. I recently had a reader request an additional feature: to automatically add a hyperlink from the Excel sheet to the newly created folders. I not only added this ability to my code, I also improved the overall code some as well.

The steps to use this macro to create folders is as follows:


  1. User selects range of cells they want to turn into folders
  2. Run macro
  3. Select location where folders will be created
  4. Macro automatically creates folders and hyperlinks selected cell to newly created folder


Here is a screen capture video of the VBA in action:


You can download the exact same spreadsheet template I use in the video here.

Or you can copy and paste the code below into your own Excel file. I use comments to explain what us happening on each line of code.

Sub Create_Folders()
'remember to select the cells you want to turn into folders before running the macro

'Default location where to select folder
Dim OpenAt As String
OpenAt = "My computer:\"

'Dialog box to select folder creation location
Set ShellApp = CreateObject("Shell.Application").BrowseForFolder(0, "Please Choose The Folder For This Project", 0, OpenAt)

'Set the folder to that selected. (On error in case cancelled)
On Error Resume Next
BrowseForFolder = ShellApp.Self.Path

'get the range of cells that were selected before the macro was run
Dim Rng As Range
Dim maxRows, maxCols, r, c As Integer
Set Rng = Selection
maxRows = Rng.Rows.Count
maxCols = Rng.Columns.Count

'---loop through all cells within selected range---
For c = 1 To maxCols
   r = 1
   Do While r <= maxRows
  
       'if the selected cell does not contain nothing, then create a folder
       If Rng(r, c) <> "" Then

           'create hyperlink in Excel file to newly created folder
           Dim cnf
           Set cnf = CreateObject("Scripting.FileSystemObject")

               'If folder already exists in this location, then just create hyperlink in Excel

               If (cnf.FolderExists(BrowseForFolder & "\" & Rng(r, c))) Then
       
               'MsgBox "folder does  already exist"
              ActiveSheet.Hyperlinks.Add Anchor:=Rng(r, c), Address:=BrowseForFolder & "\" & Rng(r, c)
   
               'if folder does not previously exist, then we need to create it and add hyperlink
               Else
               'MsgBox "need to create folder"
               cnf.CreateFolder (BrowseForFolder & "\" & Rng(r, c))
              ActiveSheet.Hyperlinks.Add Anchor:=Rng(r, c), Address:=BrowseForFolder & "\" & Rng(r, c)
               End If

           On Error Resume Next
   
       'if the selected cell contains nothing, then do nothing and go to the next cell
       End If
      
       r = r + 1
       Loop
   Next c
End Sub

Follow my Excel Help playlist for more how to videos in the future.